es6.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752
  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. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides 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.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * 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)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * 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
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._observers.splice(index, 1);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this.remove(observer);
  8218. });
  8219. };
  8220. /**
  8221. * Notify all Observers by calling their respective callback with the given data
  8222. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8223. * @param eventData defines the data to send to all observers
  8224. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8225. * @param target defines the original target of the state
  8226. * @param currentTarget defines the current target of the state
  8227. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8228. */
  8229. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8230. if (mask === void 0) { mask = -1; }
  8231. if (!this._observers.length) {
  8232. return true;
  8233. }
  8234. var state = this._eventState;
  8235. state.mask = mask;
  8236. state.target = target;
  8237. state.currentTarget = currentTarget;
  8238. state.skipNextObservers = false;
  8239. state.lastReturnValue = eventData;
  8240. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8241. var obs = _a[_i];
  8242. if (obs._willBeUnregistered) {
  8243. continue;
  8244. }
  8245. if (obs.mask & mask) {
  8246. if (obs.scope) {
  8247. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8248. }
  8249. else {
  8250. state.lastReturnValue = obs.callback(eventData, state);
  8251. }
  8252. if (obs.unregisterOnNextCall) {
  8253. this._deferUnregister(obs);
  8254. }
  8255. }
  8256. if (state.skipNextObservers) {
  8257. return false;
  8258. }
  8259. }
  8260. return true;
  8261. };
  8262. /**
  8263. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8264. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8265. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8266. * and it is crucial that all callbacks will be executed.
  8267. * The order of the callbacks is kept, callbacks are not executed parallel.
  8268. *
  8269. * @param eventData The data to be sent to each callback
  8270. * @param mask is used to filter observers defaults to -1
  8271. * @param target defines the callback target (see EventState)
  8272. * @param currentTarget defines he current object in the bubbling phase
  8273. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8274. */
  8275. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8276. var _this = this;
  8277. if (mask === void 0) { mask = -1; }
  8278. // create an empty promise
  8279. var p = Promise.resolve(eventData);
  8280. // no observers? return this promise.
  8281. if (!this._observers.length) {
  8282. return p;
  8283. }
  8284. var state = this._eventState;
  8285. state.mask = mask;
  8286. state.target = target;
  8287. state.currentTarget = currentTarget;
  8288. state.skipNextObservers = false;
  8289. // execute one callback after another (not using Promise.all, the order is important)
  8290. this._observers.forEach(function (obs) {
  8291. if (state.skipNextObservers) {
  8292. return;
  8293. }
  8294. if (obs._willBeUnregistered) {
  8295. return;
  8296. }
  8297. if (obs.mask & mask) {
  8298. if (obs.scope) {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback.apply(obs.scope, [eventData, state]);
  8302. });
  8303. }
  8304. else {
  8305. p = p.then(function (lastReturnedValue) {
  8306. state.lastReturnValue = lastReturnedValue;
  8307. return obs.callback(eventData, state);
  8308. });
  8309. }
  8310. if (obs.unregisterOnNextCall) {
  8311. _this._deferUnregister(obs);
  8312. }
  8313. }
  8314. });
  8315. // return the eventData
  8316. return p.then(function () { return eventData; });
  8317. };
  8318. /**
  8319. * Notify a specific observer
  8320. * @param observer defines the observer to notify
  8321. * @param eventData defines the data to be sent to each callback
  8322. * @param mask is used to filter observers defaults to -1
  8323. */
  8324. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8325. if (mask === void 0) { mask = -1; }
  8326. var state = this._eventState;
  8327. state.mask = mask;
  8328. state.skipNextObservers = false;
  8329. observer.callback(eventData, state);
  8330. };
  8331. /**
  8332. * Gets a boolean indicating if the observable has at least one observer
  8333. * @returns true is the Observable has at least one Observer registered
  8334. */
  8335. Observable.prototype.hasObservers = function () {
  8336. return this._observers.length > 0;
  8337. };
  8338. /**
  8339. * Clear the list of observers
  8340. */
  8341. Observable.prototype.clear = function () {
  8342. this._observers = new Array();
  8343. this._onObserverAdded = null;
  8344. };
  8345. /**
  8346. * Clone the current observable
  8347. * @returns a new observable
  8348. */
  8349. Observable.prototype.clone = function () {
  8350. var result = new Observable();
  8351. result._observers = this._observers.slice(0);
  8352. return result;
  8353. };
  8354. /**
  8355. * Does this observable handles observer registered with a given mask
  8356. * @param mask defines the mask to be tested
  8357. * @return whether or not one observer registered with the given mask is handeled
  8358. **/
  8359. Observable.prototype.hasSpecificMask = function (mask) {
  8360. if (mask === void 0) { mask = -1; }
  8361. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8362. var obs = _a[_i];
  8363. if (obs.mask & mask || obs.mask === mask) {
  8364. return true;
  8365. }
  8366. }
  8367. return false;
  8368. };
  8369. return Observable;
  8370. }());
  8371. BABYLON.Observable = Observable;
  8372. })(BABYLON || (BABYLON = {}));
  8373. //# sourceMappingURL=babylon.observable.js.map
  8374. var BABYLON;
  8375. (function (BABYLON) {
  8376. var SmartArray = /** @class */ (function () {
  8377. function SmartArray(capacity) {
  8378. this.length = 0;
  8379. this.data = new Array(capacity);
  8380. this._id = SmartArray._GlobalId++;
  8381. }
  8382. SmartArray.prototype.push = function (value) {
  8383. this.data[this.length++] = value;
  8384. if (this.length > this.data.length) {
  8385. this.data.length *= 2;
  8386. }
  8387. };
  8388. SmartArray.prototype.forEach = function (func) {
  8389. for (var index = 0; index < this.length; index++) {
  8390. func(this.data[index]);
  8391. }
  8392. };
  8393. SmartArray.prototype.sort = function (compareFn) {
  8394. this.data.sort(compareFn);
  8395. };
  8396. SmartArray.prototype.reset = function () {
  8397. this.length = 0;
  8398. };
  8399. SmartArray.prototype.dispose = function () {
  8400. this.reset();
  8401. if (this.data) {
  8402. this.data.length = 0;
  8403. this.data = [];
  8404. }
  8405. };
  8406. SmartArray.prototype.concat = function (array) {
  8407. if (array.length === 0) {
  8408. return;
  8409. }
  8410. if (this.length + array.length > this.data.length) {
  8411. this.data.length = (this.length + array.length) * 2;
  8412. }
  8413. for (var index = 0; index < array.length; index++) {
  8414. this.data[this.length++] = (array.data || array)[index];
  8415. }
  8416. };
  8417. SmartArray.prototype.indexOf = function (value) {
  8418. var position = this.data.indexOf(value);
  8419. if (position >= this.length) {
  8420. return -1;
  8421. }
  8422. return position;
  8423. };
  8424. SmartArray.prototype.contains = function (value) {
  8425. return this.data.indexOf(value) !== -1;
  8426. };
  8427. // Statics
  8428. SmartArray._GlobalId = 0;
  8429. return SmartArray;
  8430. }());
  8431. BABYLON.SmartArray = SmartArray;
  8432. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8433. __extends(SmartArrayNoDuplicate, _super);
  8434. function SmartArrayNoDuplicate() {
  8435. var _this = _super !== null && _super.apply(this, arguments) || this;
  8436. _this._duplicateId = 0;
  8437. return _this;
  8438. }
  8439. SmartArrayNoDuplicate.prototype.push = function (value) {
  8440. _super.prototype.push.call(this, value);
  8441. if (!value.__smartArrayFlags) {
  8442. value.__smartArrayFlags = {};
  8443. }
  8444. value.__smartArrayFlags[this._id] = this._duplicateId;
  8445. };
  8446. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8447. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8448. return false;
  8449. }
  8450. this.push(value);
  8451. return true;
  8452. };
  8453. SmartArrayNoDuplicate.prototype.reset = function () {
  8454. _super.prototype.reset.call(this);
  8455. this._duplicateId++;
  8456. };
  8457. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8458. if (array.length === 0) {
  8459. return;
  8460. }
  8461. if (this.length + array.length > this.data.length) {
  8462. this.data.length = (this.length + array.length) * 2;
  8463. }
  8464. for (var index = 0; index < array.length; index++) {
  8465. var item = (array.data || array)[index];
  8466. this.pushNoDuplicate(item);
  8467. }
  8468. };
  8469. return SmartArrayNoDuplicate;
  8470. }(SmartArray));
  8471. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8472. })(BABYLON || (BABYLON = {}));
  8473. //# sourceMappingURL=babylon.smartArray.js.map
  8474. var BABYLON;
  8475. (function (BABYLON) {
  8476. /** Class used to store color gradient */
  8477. var ColorGradient = /** @class */ (function () {
  8478. function ColorGradient() {
  8479. }
  8480. /**
  8481. * Will get a color picked randomly between color1 and color2.
  8482. * If color2 is undefined then color1 will be used
  8483. * @param result defines the target Color4 to store the result in
  8484. */
  8485. ColorGradient.prototype.getColorToRef = function (result) {
  8486. if (!this.color2) {
  8487. result.copyFrom(this.color1);
  8488. return;
  8489. }
  8490. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8491. };
  8492. return ColorGradient;
  8493. }());
  8494. BABYLON.ColorGradient = ColorGradient;
  8495. /** Class used to store factor gradient */
  8496. var FactorGradient = /** @class */ (function () {
  8497. function FactorGradient() {
  8498. }
  8499. return FactorGradient;
  8500. }());
  8501. BABYLON.FactorGradient = FactorGradient;
  8502. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8503. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8504. var LoadFileError = /** @class */ (function (_super) {
  8505. __extends(LoadFileError, _super);
  8506. function LoadFileError(message, request) {
  8507. var _this = _super.call(this, message) || this;
  8508. _this.request = request;
  8509. _this.name = "LoadFileError";
  8510. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8511. return _this;
  8512. }
  8513. // Polyfill for Object.setPrototypeOf if necessary.
  8514. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8515. return LoadFileError;
  8516. }(Error));
  8517. BABYLON.LoadFileError = LoadFileError;
  8518. var RetryStrategy = /** @class */ (function () {
  8519. function RetryStrategy() {
  8520. }
  8521. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8522. if (maxRetries === void 0) { maxRetries = 3; }
  8523. if (baseInterval === void 0) { baseInterval = 500; }
  8524. return function (url, request, retryIndex) {
  8525. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8526. return -1;
  8527. }
  8528. return Math.pow(2, retryIndex) * baseInterval;
  8529. };
  8530. };
  8531. return RetryStrategy;
  8532. }());
  8533. BABYLON.RetryStrategy = RetryStrategy;
  8534. // Screenshots
  8535. var screenshotCanvas;
  8536. var cloneValue = function (source, destinationObject) {
  8537. if (!source)
  8538. return null;
  8539. if (source instanceof BABYLON.Mesh) {
  8540. return null;
  8541. }
  8542. if (source instanceof BABYLON.SubMesh) {
  8543. return source.clone(destinationObject);
  8544. }
  8545. else if (source.clone) {
  8546. return source.clone();
  8547. }
  8548. return null;
  8549. };
  8550. var Tools = /** @class */ (function () {
  8551. function Tools() {
  8552. }
  8553. /**
  8554. * Interpolates between a and b via alpha
  8555. * @param a The lower value (returned when alpha = 0)
  8556. * @param b The upper value (returned when alpha = 1)
  8557. * @param alpha The interpolation-factor
  8558. * @return The mixed value
  8559. */
  8560. Tools.Mix = function (a, b, alpha) {
  8561. return a * (1 - alpha) + b * alpha;
  8562. };
  8563. Tools.Instantiate = function (className) {
  8564. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8565. return Tools.RegisteredExternalClasses[className];
  8566. }
  8567. var arr = className.split(".");
  8568. var fn = (window || this);
  8569. for (var i = 0, len = arr.length; i < len; i++) {
  8570. fn = fn[arr[i]];
  8571. }
  8572. if (typeof fn !== "function") {
  8573. return null;
  8574. }
  8575. return fn;
  8576. };
  8577. /**
  8578. * Provides a slice function that will work even on IE
  8579. * @param data defines the array to slice
  8580. * @param start defines the start of the data (optional)
  8581. * @param end defines the end of the data (optional)
  8582. * @returns the new sliced array
  8583. */
  8584. Tools.Slice = function (data, start, end) {
  8585. if (data.slice) {
  8586. return data.slice(start, end);
  8587. }
  8588. return Array.prototype.slice.call(data, start, end);
  8589. };
  8590. Tools.SetImmediate = function (action) {
  8591. if (window.setImmediate) {
  8592. window.setImmediate(action);
  8593. }
  8594. else {
  8595. setTimeout(action, 1);
  8596. }
  8597. };
  8598. Tools.IsExponentOfTwo = function (value) {
  8599. var count = 1;
  8600. do {
  8601. count *= 2;
  8602. } while (count < value);
  8603. return count === value;
  8604. };
  8605. /**
  8606. * Returns the nearest 32-bit single precision float representation of a Number
  8607. * @param value A Number. If the parameter is of a different type, it will get converted
  8608. * to a number or to NaN if it cannot be converted
  8609. * @returns number
  8610. */
  8611. Tools.FloatRound = function (value) {
  8612. if (Math.fround) {
  8613. return Math.fround(value);
  8614. }
  8615. return (Tools._tmpFloatArray[0] = value);
  8616. };
  8617. /**
  8618. * Find the next highest power of two.
  8619. * @param x Number to start search from.
  8620. * @return Next highest power of two.
  8621. */
  8622. Tools.CeilingPOT = function (x) {
  8623. x--;
  8624. x |= x >> 1;
  8625. x |= x >> 2;
  8626. x |= x >> 4;
  8627. x |= x >> 8;
  8628. x |= x >> 16;
  8629. x++;
  8630. return x;
  8631. };
  8632. /**
  8633. * Find the next lowest power of two.
  8634. * @param x Number to start search from.
  8635. * @return Next lowest power of two.
  8636. */
  8637. Tools.FloorPOT = function (x) {
  8638. x = x | (x >> 1);
  8639. x = x | (x >> 2);
  8640. x = x | (x >> 4);
  8641. x = x | (x >> 8);
  8642. x = x | (x >> 16);
  8643. return x - (x >> 1);
  8644. };
  8645. /**
  8646. * Find the nearest power of two.
  8647. * @param x Number to start search from.
  8648. * @return Next nearest power of two.
  8649. */
  8650. Tools.NearestPOT = function (x) {
  8651. var c = Tools.CeilingPOT(x);
  8652. var f = Tools.FloorPOT(x);
  8653. return (c - x) > (x - f) ? f : c;
  8654. };
  8655. Tools.GetExponentOfTwo = function (value, max, mode) {
  8656. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8657. var pot;
  8658. switch (mode) {
  8659. case BABYLON.Engine.SCALEMODE_FLOOR:
  8660. pot = Tools.FloorPOT(value);
  8661. break;
  8662. case BABYLON.Engine.SCALEMODE_NEAREST:
  8663. pot = Tools.NearestPOT(value);
  8664. break;
  8665. case BABYLON.Engine.SCALEMODE_CEILING:
  8666. default:
  8667. pot = Tools.CeilingPOT(value);
  8668. break;
  8669. }
  8670. return Math.min(pot, max);
  8671. };
  8672. Tools.GetFilename = function (path) {
  8673. var index = path.lastIndexOf("/");
  8674. if (index < 0)
  8675. return path;
  8676. return path.substring(index + 1);
  8677. };
  8678. /**
  8679. * Extracts the "folder" part of a path (everything before the filename).
  8680. * @param uri The URI to extract the info from
  8681. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8682. * @returns The "folder" part of the path
  8683. */
  8684. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8685. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8686. var index = uri.lastIndexOf("/");
  8687. if (index < 0) {
  8688. if (returnUnchangedIfNoSlash) {
  8689. return uri;
  8690. }
  8691. return "";
  8692. }
  8693. return uri.substring(0, index + 1);
  8694. };
  8695. Tools.GetDOMTextContent = function (element) {
  8696. var result = "";
  8697. var child = element.firstChild;
  8698. while (child) {
  8699. if (child.nodeType === 3) {
  8700. result += child.textContent;
  8701. }
  8702. child = child.nextSibling;
  8703. }
  8704. return result;
  8705. };
  8706. Tools.ToDegrees = function (angle) {
  8707. return angle * 180 / Math.PI;
  8708. };
  8709. Tools.ToRadians = function (angle) {
  8710. return angle * Math.PI / 180;
  8711. };
  8712. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8713. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8714. var output = "";
  8715. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8716. var i = 0;
  8717. var bytes = new Uint8Array(buffer);
  8718. while (i < bytes.length) {
  8719. chr1 = bytes[i++];
  8720. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8721. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8722. enc1 = chr1 >> 2;
  8723. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8724. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8725. enc4 = chr3 & 63;
  8726. if (isNaN(chr2)) {
  8727. enc3 = enc4 = 64;
  8728. }
  8729. else if (isNaN(chr3)) {
  8730. enc4 = 64;
  8731. }
  8732. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8733. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8734. }
  8735. return "data:image/png;base64," + output;
  8736. };
  8737. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8738. if (bias === void 0) { bias = null; }
  8739. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8740. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8741. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8742. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8743. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8744. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8745. }
  8746. if (bias) {
  8747. minimum.x -= minimum.x * bias.x + bias.y;
  8748. minimum.y -= minimum.y * bias.x + bias.y;
  8749. minimum.z -= minimum.z * bias.x + bias.y;
  8750. maximum.x += maximum.x * bias.x + bias.y;
  8751. maximum.y += maximum.y * bias.x + bias.y;
  8752. maximum.z += maximum.z * bias.x + bias.y;
  8753. }
  8754. return {
  8755. minimum: minimum,
  8756. maximum: maximum
  8757. };
  8758. };
  8759. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8760. if (bias === void 0) { bias = null; }
  8761. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8762. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8763. if (!stride) {
  8764. stride = 3;
  8765. }
  8766. for (var index = start; index < start + count; index++) {
  8767. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8768. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8769. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. minimum.z -= minimum.z * bias.x + bias.y;
  8775. maximum.x += maximum.x * bias.x + bias.y;
  8776. maximum.y += maximum.y * bias.x + bias.y;
  8777. maximum.z += maximum.z * bias.x + bias.y;
  8778. }
  8779. return {
  8780. minimum: minimum,
  8781. maximum: maximum
  8782. };
  8783. };
  8784. Tools.Vector2ArrayFeeder = function (array) {
  8785. return function (index) {
  8786. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8787. var length = isFloatArray ? array.length / 2 : array.length;
  8788. if (index >= length) {
  8789. return null;
  8790. }
  8791. if (isFloatArray) {
  8792. var fa = array;
  8793. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8794. }
  8795. var a = array;
  8796. return a[index];
  8797. };
  8798. };
  8799. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8800. if (bias === void 0) { bias = null; }
  8801. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8802. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8803. var i = 0;
  8804. var cur = feeder(i++);
  8805. while (cur) {
  8806. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8807. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8808. cur = feeder(i++);
  8809. }
  8810. if (bias) {
  8811. minimum.x -= minimum.x * bias.x + bias.y;
  8812. minimum.y -= minimum.y * bias.x + bias.y;
  8813. maximum.x += maximum.x * bias.x + bias.y;
  8814. maximum.y += maximum.y * bias.x + bias.y;
  8815. }
  8816. return {
  8817. minimum: minimum,
  8818. maximum: maximum
  8819. };
  8820. };
  8821. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8822. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8823. return null;
  8824. return Array.isArray(obj) ? obj : [obj];
  8825. };
  8826. // Misc.
  8827. Tools.GetPointerPrefix = function () {
  8828. var eventPrefix = "pointer";
  8829. // Check if pointer events are supported
  8830. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8831. eventPrefix = "mouse";
  8832. }
  8833. return eventPrefix;
  8834. };
  8835. /**
  8836. * @param func - the function to be called
  8837. * @param requester - the object that will request the next frame. Falls back to window.
  8838. */
  8839. Tools.QueueNewFrame = function (func, requester) {
  8840. if (!Tools.IsWindowObjectExist()) {
  8841. return setTimeout(func, 16);
  8842. }
  8843. if (!requester) {
  8844. requester = window;
  8845. }
  8846. if (requester.requestAnimationFrame) {
  8847. return requester.requestAnimationFrame(func);
  8848. }
  8849. else if (requester.msRequestAnimationFrame) {
  8850. return requester.msRequestAnimationFrame(func);
  8851. }
  8852. else if (requester.webkitRequestAnimationFrame) {
  8853. return requester.webkitRequestAnimationFrame(func);
  8854. }
  8855. else if (requester.mozRequestAnimationFrame) {
  8856. return requester.mozRequestAnimationFrame(func);
  8857. }
  8858. else if (requester.oRequestAnimationFrame) {
  8859. return requester.oRequestAnimationFrame(func);
  8860. }
  8861. else {
  8862. return window.setTimeout(func, 16);
  8863. }
  8864. };
  8865. Tools.RequestFullscreen = function (element) {
  8866. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8867. if (!requestFunction)
  8868. return;
  8869. requestFunction.call(element);
  8870. };
  8871. Tools.ExitFullscreen = function () {
  8872. if (document.exitFullscreen) {
  8873. document.exitFullscreen();
  8874. }
  8875. else if (document.mozCancelFullScreen) {
  8876. document.mozCancelFullScreen();
  8877. }
  8878. else if (document.webkitCancelFullScreen) {
  8879. document.webkitCancelFullScreen();
  8880. }
  8881. else if (document.msCancelFullScreen) {
  8882. document.msCancelFullScreen();
  8883. }
  8884. };
  8885. Tools.SetCorsBehavior = function (url, element) {
  8886. if (url && url.indexOf("data:") === 0) {
  8887. return;
  8888. }
  8889. if (Tools.CorsBehavior) {
  8890. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8891. element.crossOrigin = Tools.CorsBehavior;
  8892. }
  8893. else {
  8894. var result = Tools.CorsBehavior(url);
  8895. if (result) {
  8896. element.crossOrigin = result;
  8897. }
  8898. }
  8899. }
  8900. };
  8901. // External files
  8902. Tools.CleanUrl = function (url) {
  8903. url = url.replace(/#/mg, "%23");
  8904. return url;
  8905. };
  8906. /**
  8907. * Loads an image as an HTMLImageElement.
  8908. * @param input url string, ArrayBuffer, or Blob to load
  8909. * @param onLoad callback called when the image successfully loads
  8910. * @param onError callback called when the image fails to load
  8911. * @param database database for caching
  8912. * @returns the HTMLImageElement of the loaded image
  8913. */
  8914. Tools.LoadImage = function (input, onLoad, onError, database) {
  8915. var url;
  8916. var usingObjectURL = false;
  8917. if (input instanceof ArrayBuffer) {
  8918. url = URL.createObjectURL(new Blob([input]));
  8919. usingObjectURL = true;
  8920. }
  8921. else if (input instanceof Blob) {
  8922. url = URL.createObjectURL(input);
  8923. usingObjectURL = true;
  8924. }
  8925. else {
  8926. url = Tools.CleanUrl(input);
  8927. url = Tools.PreprocessUrl(input);
  8928. }
  8929. var img = new Image();
  8930. Tools.SetCorsBehavior(url, img);
  8931. var loadHandler = function () {
  8932. if (usingObjectURL && img.src) {
  8933. URL.revokeObjectURL(img.src);
  8934. }
  8935. img.removeEventListener("load", loadHandler);
  8936. img.removeEventListener("error", errorHandler);
  8937. onLoad(img);
  8938. };
  8939. var errorHandler = function (err) {
  8940. if (usingObjectURL && img.src) {
  8941. URL.revokeObjectURL(img.src);
  8942. }
  8943. img.removeEventListener("load", loadHandler);
  8944. img.removeEventListener("error", errorHandler);
  8945. Tools.Error("Error while trying to load image: " + input);
  8946. if (onError) {
  8947. onError("Error while trying to load image: " + input, err);
  8948. }
  8949. };
  8950. img.addEventListener("load", loadHandler);
  8951. img.addEventListener("error", errorHandler);
  8952. var noIndexedDB = function () {
  8953. img.src = url;
  8954. };
  8955. var loadFromIndexedDB = function () {
  8956. if (database) {
  8957. database.loadImageFromDB(url, img);
  8958. }
  8959. };
  8960. //ANY database to do!
  8961. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8962. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8963. }
  8964. else {
  8965. if (url.indexOf("file:") !== -1) {
  8966. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8967. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8968. try {
  8969. var blobURL;
  8970. try {
  8971. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8972. }
  8973. catch (ex) {
  8974. // Chrome doesn't support oneTimeOnly parameter
  8975. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8976. }
  8977. img.src = blobURL;
  8978. usingObjectURL = true;
  8979. }
  8980. catch (e) {
  8981. img.src = "";
  8982. }
  8983. return img;
  8984. }
  8985. }
  8986. noIndexedDB();
  8987. }
  8988. return img;
  8989. };
  8990. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8991. url = Tools.CleanUrl(url);
  8992. url = Tools.PreprocessUrl(url);
  8993. // If file and file input are set
  8994. if (url.indexOf("file:") !== -1) {
  8995. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8996. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8997. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8998. }
  8999. }
  9000. var loadUrl = Tools.BaseUrl + url;
  9001. var aborted = false;
  9002. var fileRequest = {
  9003. onCompleteObservable: new BABYLON.Observable(),
  9004. abort: function () { return aborted = true; },
  9005. };
  9006. var requestFile = function () {
  9007. var request = new XMLHttpRequest();
  9008. var retryHandle = null;
  9009. fileRequest.abort = function () {
  9010. aborted = true;
  9011. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9012. request.abort();
  9013. }
  9014. if (retryHandle !== null) {
  9015. clearTimeout(retryHandle);
  9016. retryHandle = null;
  9017. }
  9018. };
  9019. var retryLoop = function (retryIndex) {
  9020. request.open('GET', loadUrl, true);
  9021. if (useArrayBuffer) {
  9022. request.responseType = "arraybuffer";
  9023. }
  9024. if (onProgress) {
  9025. request.addEventListener("progress", onProgress);
  9026. }
  9027. var onLoadEnd = function () {
  9028. request.removeEventListener("loadend", onLoadEnd);
  9029. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9030. fileRequest.onCompleteObservable.clear();
  9031. };
  9032. request.addEventListener("loadend", onLoadEnd);
  9033. var onReadyStateChange = function () {
  9034. if (aborted) {
  9035. return;
  9036. }
  9037. // In case of undefined state in some browsers.
  9038. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9039. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9040. request.removeEventListener("readystatechange", onReadyStateChange);
  9041. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9042. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9043. return;
  9044. }
  9045. var retryStrategy = Tools.DefaultRetryStrategy;
  9046. if (retryStrategy) {
  9047. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9048. if (waitTime !== -1) {
  9049. // Prevent the request from completing for retry.
  9050. request.removeEventListener("loadend", onLoadEnd);
  9051. request = new XMLHttpRequest();
  9052. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9053. return;
  9054. }
  9055. }
  9056. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9057. if (onError) {
  9058. onError(request, e);
  9059. }
  9060. else {
  9061. throw e;
  9062. }
  9063. }
  9064. };
  9065. request.addEventListener("readystatechange", onReadyStateChange);
  9066. request.send();
  9067. };
  9068. retryLoop(0);
  9069. };
  9070. // Caching all files
  9071. if (database && database.enableSceneOffline) {
  9072. var noIndexedDB_1 = function () {
  9073. if (!aborted) {
  9074. requestFile();
  9075. }
  9076. };
  9077. var loadFromIndexedDB = function () {
  9078. // TODO: database needs to support aborting and should return a IFileRequest
  9079. if (aborted) {
  9080. return;
  9081. }
  9082. if (database) {
  9083. database.loadFileFromDB(url, function (data) {
  9084. if (!aborted) {
  9085. onSuccess(data);
  9086. }
  9087. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9088. }, onProgress ? function (event) {
  9089. if (!aborted) {
  9090. onProgress(event);
  9091. }
  9092. } : undefined, noIndexedDB_1, useArrayBuffer);
  9093. }
  9094. };
  9095. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9096. }
  9097. else {
  9098. requestFile();
  9099. }
  9100. return fileRequest;
  9101. };
  9102. /**
  9103. * Load a script (identified by an url). When the url returns, the
  9104. * content of this file is added into a new script element, attached to the DOM (body element)
  9105. */
  9106. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9107. var head = document.getElementsByTagName('head')[0];
  9108. var script = document.createElement('script');
  9109. script.type = 'text/javascript';
  9110. script.src = scriptUrl;
  9111. script.onload = function () {
  9112. if (onSuccess) {
  9113. onSuccess();
  9114. }
  9115. };
  9116. script.onerror = function (e) {
  9117. if (onError) {
  9118. onError("Unable to load script '" + scriptUrl + "'", e);
  9119. }
  9120. };
  9121. head.appendChild(script);
  9122. };
  9123. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9124. var reader = new FileReader();
  9125. var request = {
  9126. onCompleteObservable: new BABYLON.Observable(),
  9127. abort: function () { return reader.abort(); },
  9128. };
  9129. reader.onloadend = function (e) {
  9130. request.onCompleteObservable.notifyObservers(request);
  9131. };
  9132. reader.onload = function (e) {
  9133. //target doesn't have result from ts 1.3
  9134. callback(e.target['result']);
  9135. };
  9136. reader.onprogress = progressCallback;
  9137. reader.readAsDataURL(fileToLoad);
  9138. return request;
  9139. };
  9140. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9141. var reader = new FileReader();
  9142. var request = {
  9143. onCompleteObservable: new BABYLON.Observable(),
  9144. abort: function () { return reader.abort(); },
  9145. };
  9146. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9147. reader.onerror = function (e) {
  9148. Tools.Log("Error while reading file: " + fileToLoad.name);
  9149. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9150. };
  9151. reader.onload = function (e) {
  9152. //target doesn't have result from ts 1.3
  9153. callback(e.target['result']);
  9154. };
  9155. if (progressCallBack) {
  9156. reader.onprogress = progressCallBack;
  9157. }
  9158. if (!useArrayBuffer) {
  9159. // Asynchronous read
  9160. reader.readAsText(fileToLoad);
  9161. }
  9162. else {
  9163. reader.readAsArrayBuffer(fileToLoad);
  9164. }
  9165. return request;
  9166. };
  9167. //returns a downloadable url to a file content.
  9168. Tools.FileAsURL = function (content) {
  9169. var fileBlob = new Blob([content]);
  9170. var url = window.URL || window.webkitURL;
  9171. var link = url.createObjectURL(fileBlob);
  9172. return link;
  9173. };
  9174. // Misc.
  9175. Tools.Format = function (value, decimals) {
  9176. if (decimals === void 0) { decimals = 2; }
  9177. return value.toFixed(decimals);
  9178. };
  9179. Tools.CheckExtends = function (v, min, max) {
  9180. if (v.x < min.x)
  9181. min.x = v.x;
  9182. if (v.y < min.y)
  9183. min.y = v.y;
  9184. if (v.z < min.z)
  9185. min.z = v.z;
  9186. if (v.x > max.x)
  9187. max.x = v.x;
  9188. if (v.y > max.y)
  9189. max.y = v.y;
  9190. if (v.z > max.z)
  9191. max.z = v.z;
  9192. };
  9193. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9194. for (var prop in source) {
  9195. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9196. continue;
  9197. }
  9198. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9199. continue;
  9200. }
  9201. var sourceValue = source[prop];
  9202. var typeOfSourceValue = typeof sourceValue;
  9203. if (typeOfSourceValue === "function") {
  9204. continue;
  9205. }
  9206. try {
  9207. if (typeOfSourceValue === "object") {
  9208. if (sourceValue instanceof Array) {
  9209. destination[prop] = [];
  9210. if (sourceValue.length > 0) {
  9211. if (typeof sourceValue[0] == "object") {
  9212. for (var index = 0; index < sourceValue.length; index++) {
  9213. var clonedValue = cloneValue(sourceValue[index], destination);
  9214. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9215. destination[prop].push(clonedValue);
  9216. }
  9217. }
  9218. }
  9219. else {
  9220. destination[prop] = sourceValue.slice(0);
  9221. }
  9222. }
  9223. }
  9224. else {
  9225. destination[prop] = cloneValue(sourceValue, destination);
  9226. }
  9227. }
  9228. else {
  9229. destination[prop] = sourceValue;
  9230. }
  9231. }
  9232. catch (e) {
  9233. // Just ignore error (it could be because of a read-only property)
  9234. }
  9235. }
  9236. };
  9237. Tools.IsEmpty = function (obj) {
  9238. for (var i in obj) {
  9239. if (obj.hasOwnProperty(i)) {
  9240. return false;
  9241. }
  9242. }
  9243. return true;
  9244. };
  9245. Tools.RegisterTopRootEvents = function (events) {
  9246. for (var index = 0; index < events.length; index++) {
  9247. var event = events[index];
  9248. window.addEventListener(event.name, event.handler, false);
  9249. try {
  9250. if (window.parent) {
  9251. window.parent.addEventListener(event.name, event.handler, false);
  9252. }
  9253. }
  9254. catch (e) {
  9255. // Silently fails...
  9256. }
  9257. }
  9258. };
  9259. Tools.UnregisterTopRootEvents = function (events) {
  9260. for (var index = 0; index < events.length; index++) {
  9261. var event = events[index];
  9262. window.removeEventListener(event.name, event.handler);
  9263. try {
  9264. if (window.parent) {
  9265. window.parent.removeEventListener(event.name, event.handler);
  9266. }
  9267. }
  9268. catch (e) {
  9269. // Silently fails...
  9270. }
  9271. }
  9272. };
  9273. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9274. if (mimeType === void 0) { mimeType = "image/png"; }
  9275. // Read the contents of the framebuffer
  9276. var numberOfChannelsByLine = width * 4;
  9277. var halfHeight = height / 2;
  9278. //Reading datas from WebGL
  9279. var data = engine.readPixels(0, 0, width, height);
  9280. //To flip image on Y axis.
  9281. for (var i = 0; i < halfHeight; i++) {
  9282. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9283. var currentCell = j + i * numberOfChannelsByLine;
  9284. var targetLine = height - i - 1;
  9285. var targetCell = j + targetLine * numberOfChannelsByLine;
  9286. var temp = data[currentCell];
  9287. data[currentCell] = data[targetCell];
  9288. data[targetCell] = temp;
  9289. }
  9290. }
  9291. // Create a 2D canvas to store the result
  9292. if (!screenshotCanvas) {
  9293. screenshotCanvas = document.createElement('canvas');
  9294. }
  9295. screenshotCanvas.width = width;
  9296. screenshotCanvas.height = height;
  9297. var context = screenshotCanvas.getContext('2d');
  9298. if (context) {
  9299. // Copy the pixels to a 2D canvas
  9300. var imageData = context.createImageData(width, height);
  9301. var castData = (imageData.data);
  9302. castData.set(data);
  9303. context.putImageData(imageData, 0, 0);
  9304. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9305. }
  9306. };
  9307. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9308. if (mimeType === void 0) { mimeType = "image/png"; }
  9309. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9310. if (successCallback) {
  9311. successCallback(base64Image);
  9312. }
  9313. else {
  9314. // We need HTMLCanvasElement.toBlob for HD screenshots
  9315. if (!screenshotCanvas.toBlob) {
  9316. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9317. screenshotCanvas.toBlob = function (callback, type, quality) {
  9318. var _this = this;
  9319. setTimeout(function () {
  9320. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9321. for (var i = 0; i < len; i++) {
  9322. arr[i] = binStr.charCodeAt(i);
  9323. }
  9324. callback(new Blob([arr], { type: type || 'image/png' }));
  9325. });
  9326. };
  9327. }
  9328. screenshotCanvas.toBlob(function (blob) {
  9329. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9330. if (("download" in document.createElement("a"))) {
  9331. if (!fileName) {
  9332. var date = new Date();
  9333. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9334. fileName = "screenshot_" + stringDate + ".png";
  9335. }
  9336. Tools.Download(blob, fileName);
  9337. }
  9338. else {
  9339. var url = URL.createObjectURL(blob);
  9340. var newWindow = window.open("");
  9341. if (!newWindow)
  9342. return;
  9343. var img = newWindow.document.createElement("img");
  9344. img.onload = function () {
  9345. // no longer need to read the blob so it's revoked
  9346. URL.revokeObjectURL(url);
  9347. };
  9348. img.src = url;
  9349. newWindow.document.body.appendChild(img);
  9350. }
  9351. });
  9352. }
  9353. };
  9354. /**
  9355. * Downloads a blob in the browser
  9356. * @param blob defines the blob to download
  9357. * @param fileName defines the name of the downloaded file
  9358. */
  9359. Tools.Download = function (blob, fileName) {
  9360. var url = window.URL.createObjectURL(blob);
  9361. var a = document.createElement("a");
  9362. document.body.appendChild(a);
  9363. a.style.display = "none";
  9364. a.href = url;
  9365. a.download = fileName;
  9366. a.addEventListener("click", function () {
  9367. if (a.parentElement) {
  9368. a.parentElement.removeChild(a);
  9369. }
  9370. });
  9371. a.click();
  9372. window.URL.revokeObjectURL(url);
  9373. };
  9374. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9375. if (mimeType === void 0) { mimeType = "image/png"; }
  9376. var width;
  9377. var height;
  9378. // If a precision value is specified
  9379. if (size.precision) {
  9380. width = Math.round(engine.getRenderWidth() * size.precision);
  9381. height = Math.round(width / engine.getAspectRatio(camera));
  9382. }
  9383. else if (size.width && size.height) {
  9384. width = size.width;
  9385. height = size.height;
  9386. }
  9387. //If passing only width, computing height to keep display canvas ratio.
  9388. else if (size.width && !size.height) {
  9389. width = size.width;
  9390. height = Math.round(width / engine.getAspectRatio(camera));
  9391. }
  9392. //If passing only height, computing width to keep display canvas ratio.
  9393. else if (size.height && !size.width) {
  9394. height = size.height;
  9395. width = Math.round(height * engine.getAspectRatio(camera));
  9396. }
  9397. //Assuming here that "size" parameter is a number
  9398. else if (!isNaN(size)) {
  9399. height = size;
  9400. width = size;
  9401. }
  9402. else {
  9403. Tools.Error("Invalid 'size' parameter !");
  9404. return;
  9405. }
  9406. if (!screenshotCanvas) {
  9407. screenshotCanvas = document.createElement('canvas');
  9408. }
  9409. screenshotCanvas.width = width;
  9410. screenshotCanvas.height = height;
  9411. var renderContext = screenshotCanvas.getContext("2d");
  9412. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9413. var newWidth = width;
  9414. var newHeight = newWidth / ratio;
  9415. if (newHeight > height) {
  9416. newHeight = height;
  9417. newWidth = newHeight * ratio;
  9418. }
  9419. var offsetX = Math.max(0, width - newWidth) / 2;
  9420. var offsetY = Math.max(0, height - newHeight) / 2;
  9421. var renderingCanvas = engine.getRenderingCanvas();
  9422. if (renderContext && renderingCanvas) {
  9423. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9424. }
  9425. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9426. };
  9427. /**
  9428. * Generates an image screenshot from the specified camera.
  9429. *
  9430. * @param engine The engine to use for rendering
  9431. * @param camera The camera to use for rendering
  9432. * @param size This parameter can be set to a single number or to an object with the
  9433. * following (optional) properties: precision, width, height. If a single number is passed,
  9434. * it will be used for both width and height. If an object is passed, the screenshot size
  9435. * will be derived from the parameters. The precision property is a multiplier allowing
  9436. * rendering at a higher or lower resolution.
  9437. * @param successCallback The callback receives a single parameter which contains the
  9438. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9439. * src parameter of an <img> to display it.
  9440. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9441. * Check your browser for supported MIME types.
  9442. * @param samples Texture samples (default: 1)
  9443. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9444. * @param fileName A name for for the downloaded file.
  9445. * @constructor
  9446. */
  9447. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9448. if (mimeType === void 0) { mimeType = "image/png"; }
  9449. if (samples === void 0) { samples = 1; }
  9450. if (antialiasing === void 0) { antialiasing = false; }
  9451. var width;
  9452. var height;
  9453. //If a precision value is specified
  9454. if (size.precision) {
  9455. width = Math.round(engine.getRenderWidth() * size.precision);
  9456. height = Math.round(width / engine.getAspectRatio(camera));
  9457. size = { width: width, height: height };
  9458. }
  9459. else if (size.width && size.height) {
  9460. width = size.width;
  9461. height = size.height;
  9462. }
  9463. //If passing only width, computing height to keep display canvas ratio.
  9464. else if (size.width && !size.height) {
  9465. width = size.width;
  9466. height = Math.round(width / engine.getAspectRatio(camera));
  9467. size = { width: width, height: height };
  9468. }
  9469. //If passing only height, computing width to keep display canvas ratio.
  9470. else if (size.height && !size.width) {
  9471. height = size.height;
  9472. width = Math.round(height * engine.getAspectRatio(camera));
  9473. size = { width: width, height: height };
  9474. }
  9475. //Assuming here that "size" parameter is a number
  9476. else if (!isNaN(size)) {
  9477. height = size;
  9478. width = size;
  9479. }
  9480. else {
  9481. Tools.Error("Invalid 'size' parameter !");
  9482. return;
  9483. }
  9484. var scene = camera.getScene();
  9485. var previousCamera = null;
  9486. if (scene.activeCamera !== camera) {
  9487. previousCamera = scene.activeCamera;
  9488. scene.activeCamera = camera;
  9489. }
  9490. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9491. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9492. texture.renderList = null;
  9493. texture.samples = samples;
  9494. if (antialiasing) {
  9495. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9496. }
  9497. texture.onAfterRenderObservable.add(function () {
  9498. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9499. });
  9500. scene.incrementRenderId();
  9501. scene.resetCachedMaterial();
  9502. texture.render(true);
  9503. texture.dispose();
  9504. if (previousCamera) {
  9505. scene.activeCamera = previousCamera;
  9506. }
  9507. camera.getProjectionMatrix(true); // Force cache refresh;
  9508. };
  9509. // XHR response validator for local file scenario
  9510. Tools.ValidateXHRData = function (xhr, dataType) {
  9511. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9512. if (dataType === void 0) { dataType = 7; }
  9513. try {
  9514. if (dataType & 1) {
  9515. if (xhr.responseText && xhr.responseText.length > 0) {
  9516. return true;
  9517. }
  9518. else if (dataType === 1) {
  9519. return false;
  9520. }
  9521. }
  9522. if (dataType & 2) {
  9523. // Check header width and height since there is no "TGA" magic number
  9524. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9525. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9526. return true;
  9527. }
  9528. else if (dataType === 2) {
  9529. return false;
  9530. }
  9531. }
  9532. if (dataType & 4) {
  9533. // Check for the "DDS" magic number
  9534. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9535. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9536. return true;
  9537. }
  9538. else {
  9539. return false;
  9540. }
  9541. }
  9542. }
  9543. catch (e) {
  9544. // Global protection
  9545. }
  9546. return false;
  9547. };
  9548. /**
  9549. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9550. * Be aware Math.random() could cause collisions, but:
  9551. * "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"
  9552. */
  9553. Tools.RandomId = function () {
  9554. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9555. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9556. return v.toString(16);
  9557. });
  9558. };
  9559. /**
  9560. * Test if the given uri is a base64 string.
  9561. * @param uri The uri to test
  9562. * @return True if the uri is a base64 string or false otherwise.
  9563. */
  9564. Tools.IsBase64 = function (uri) {
  9565. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9566. };
  9567. /**
  9568. * Decode the given base64 uri.
  9569. * @param uri The uri to decode
  9570. * @return The decoded base64 data.
  9571. */
  9572. Tools.DecodeBase64 = function (uri) {
  9573. var decodedString = atob(uri.split(",")[1]);
  9574. var bufferLength = decodedString.length;
  9575. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9576. for (var i = 0; i < bufferLength; i++) {
  9577. bufferView[i] = decodedString.charCodeAt(i);
  9578. }
  9579. return bufferView.buffer;
  9580. };
  9581. Object.defineProperty(Tools, "NoneLogLevel", {
  9582. get: function () {
  9583. return Tools._NoneLogLevel;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Tools, "MessageLogLevel", {
  9589. get: function () {
  9590. return Tools._MessageLogLevel;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Tools, "WarningLogLevel", {
  9596. get: function () {
  9597. return Tools._WarningLogLevel;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Tools, "ErrorLogLevel", {
  9603. get: function () {
  9604. return Tools._ErrorLogLevel;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Tools, "AllLogLevel", {
  9610. get: function () {
  9611. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Tools._AddLogEntry = function (entry) {
  9617. Tools._LogCache = entry + Tools._LogCache;
  9618. if (Tools.OnNewCacheEntry) {
  9619. Tools.OnNewCacheEntry(entry);
  9620. }
  9621. };
  9622. Tools._FormatMessage = function (message) {
  9623. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9624. var date = new Date();
  9625. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9626. };
  9627. Tools._LogDisabled = function (message) {
  9628. // nothing to do
  9629. };
  9630. Tools._LogEnabled = function (message) {
  9631. var formattedMessage = Tools._FormatMessage(message);
  9632. console.log("BJS - " + formattedMessage);
  9633. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9634. Tools._AddLogEntry(entry);
  9635. };
  9636. Tools._WarnDisabled = function (message) {
  9637. // nothing to do
  9638. };
  9639. Tools._WarnEnabled = function (message) {
  9640. var formattedMessage = Tools._FormatMessage(message);
  9641. console.warn("BJS - " + formattedMessage);
  9642. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9643. Tools._AddLogEntry(entry);
  9644. };
  9645. Tools._ErrorDisabled = function (message) {
  9646. // nothing to do
  9647. };
  9648. Tools._ErrorEnabled = function (message) {
  9649. Tools.errorsCount++;
  9650. var formattedMessage = Tools._FormatMessage(message);
  9651. console.error("BJS - " + formattedMessage);
  9652. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9653. Tools._AddLogEntry(entry);
  9654. };
  9655. Object.defineProperty(Tools, "LogCache", {
  9656. get: function () {
  9657. return Tools._LogCache;
  9658. },
  9659. enumerable: true,
  9660. configurable: true
  9661. });
  9662. Tools.ClearLogCache = function () {
  9663. Tools._LogCache = "";
  9664. Tools.errorsCount = 0;
  9665. };
  9666. Object.defineProperty(Tools, "LogLevels", {
  9667. set: function (level) {
  9668. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9669. Tools.Log = Tools._LogEnabled;
  9670. }
  9671. else {
  9672. Tools.Log = Tools._LogDisabled;
  9673. }
  9674. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9675. Tools.Warn = Tools._WarnEnabled;
  9676. }
  9677. else {
  9678. Tools.Warn = Tools._WarnDisabled;
  9679. }
  9680. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9681. Tools.Error = Tools._ErrorEnabled;
  9682. }
  9683. else {
  9684. Tools.Error = Tools._ErrorDisabled;
  9685. }
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Tools.IsWindowObjectExist = function () {
  9691. return (typeof window) !== "undefined";
  9692. };
  9693. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9694. get: function () {
  9695. return Tools._PerformanceNoneLogLevel;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9701. get: function () {
  9702. return Tools._PerformanceUserMarkLogLevel;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9708. get: function () {
  9709. return Tools._PerformanceConsoleLogLevel;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9715. set: function (level) {
  9716. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9717. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9718. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9719. return;
  9720. }
  9721. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9722. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9723. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9724. return;
  9725. }
  9726. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9727. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9733. };
  9734. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9735. };
  9736. Tools._StartUserMark = function (counterName, condition) {
  9737. if (condition === void 0) { condition = true; }
  9738. if (!Tools._performance) {
  9739. if (!Tools.IsWindowObjectExist()) {
  9740. return;
  9741. }
  9742. Tools._performance = window.performance;
  9743. }
  9744. if (!condition || !Tools._performance.mark) {
  9745. return;
  9746. }
  9747. Tools._performance.mark(counterName + "-Begin");
  9748. };
  9749. Tools._EndUserMark = function (counterName, condition) {
  9750. if (condition === void 0) { condition = true; }
  9751. if (!condition || !Tools._performance.mark) {
  9752. return;
  9753. }
  9754. Tools._performance.mark(counterName + "-End");
  9755. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9756. };
  9757. Tools._StartPerformanceConsole = function (counterName, condition) {
  9758. if (condition === void 0) { condition = true; }
  9759. if (!condition) {
  9760. return;
  9761. }
  9762. Tools._StartUserMark(counterName, condition);
  9763. if (console.time) {
  9764. console.time(counterName);
  9765. }
  9766. };
  9767. Tools._EndPerformanceConsole = function (counterName, condition) {
  9768. if (condition === void 0) { condition = true; }
  9769. if (!condition) {
  9770. return;
  9771. }
  9772. Tools._EndUserMark(counterName, condition);
  9773. if (console.time) {
  9774. console.timeEnd(counterName);
  9775. }
  9776. };
  9777. Object.defineProperty(Tools, "Now", {
  9778. get: function () {
  9779. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9780. return window.performance.now();
  9781. }
  9782. return Date.now();
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. /**
  9788. * This method will return the name of the class used to create the instance of the given object.
  9789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9790. * @param object the object to get the class name from
  9791. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9792. */
  9793. Tools.GetClassName = function (object, isType) {
  9794. if (isType === void 0) { isType = false; }
  9795. var name = null;
  9796. if (!isType && object.getClassName) {
  9797. name = object.getClassName();
  9798. }
  9799. else {
  9800. if (object instanceof Object) {
  9801. var classObj = isType ? object : Object.getPrototypeOf(object);
  9802. name = classObj.constructor["__bjsclassName__"];
  9803. }
  9804. if (!name) {
  9805. name = typeof object;
  9806. }
  9807. }
  9808. return name;
  9809. };
  9810. Tools.First = function (array, predicate) {
  9811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9812. var el = array_1[_i];
  9813. if (predicate(el)) {
  9814. return el;
  9815. }
  9816. }
  9817. return null;
  9818. };
  9819. /**
  9820. * This method will return the name of the full name of the class, including its owning module (if any).
  9821. * 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).
  9822. * @param object the object to get the class name from
  9823. * @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.
  9824. */
  9825. Tools.getFullClassName = function (object, isType) {
  9826. if (isType === void 0) { isType = false; }
  9827. var className = null;
  9828. var moduleName = null;
  9829. if (!isType && object.getClassName) {
  9830. className = object.getClassName();
  9831. }
  9832. else {
  9833. if (object instanceof Object) {
  9834. var classObj = isType ? object : Object.getPrototypeOf(object);
  9835. className = classObj.constructor["__bjsclassName__"];
  9836. moduleName = classObj.constructor["__bjsmoduleName__"];
  9837. }
  9838. if (!className) {
  9839. className = typeof object;
  9840. }
  9841. }
  9842. if (!className) {
  9843. return null;
  9844. }
  9845. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9846. };
  9847. /**
  9848. * 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.
  9849. * @param array
  9850. */
  9851. Tools.arrayOrStringFeeder = function (array) {
  9852. return function (index) {
  9853. if (index >= array.length) {
  9854. return null;
  9855. }
  9856. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9857. if (val && val.getHashCode) {
  9858. val = val.getHashCode();
  9859. }
  9860. if (typeof val === "string") {
  9861. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9862. }
  9863. return val;
  9864. };
  9865. };
  9866. /**
  9867. * Compute the hashCode of a stream of number
  9868. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9869. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9870. * @return the hash code computed
  9871. */
  9872. Tools.hashCodeFromStream = function (feeder) {
  9873. // Based from here: http://stackoverflow.com/a/7616484/802124
  9874. var hash = 0;
  9875. var index = 0;
  9876. var chr = feeder(index++);
  9877. while (chr != null) {
  9878. hash = ((hash << 5) - hash) + chr;
  9879. hash |= 0; // Convert to 32bit integer
  9880. chr = feeder(index++);
  9881. }
  9882. return hash;
  9883. };
  9884. /**
  9885. * Returns a promise that resolves after the given amount of time.
  9886. * @param delay Number of milliseconds to delay
  9887. * @returns Promise that resolves after the given amount of time
  9888. */
  9889. Tools.DelayAsync = function (delay) {
  9890. return new Promise(function (resolve) {
  9891. setTimeout(function () {
  9892. resolve();
  9893. }, delay);
  9894. });
  9895. };
  9896. /**
  9897. * Gets the current gradient from an array of IValueGradient
  9898. * @param ratio defines the current ratio to get
  9899. * @param gradients defines the array of IValueGradient
  9900. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9901. */
  9902. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9903. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9904. var currentGradient = gradients[gradientIndex];
  9905. var nextGradient = gradients[gradientIndex + 1];
  9906. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9907. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9908. updateFunc(currentGradient, nextGradient, scale);
  9909. }
  9910. }
  9911. };
  9912. Tools.BaseUrl = "";
  9913. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9914. /**
  9915. * Default behaviour for cors in the application.
  9916. * It can be a string if the expected behavior is identical in the entire app.
  9917. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9918. */
  9919. Tools.CorsBehavior = "anonymous";
  9920. Tools.UseFallbackTexture = true;
  9921. /**
  9922. * Use this object to register external classes like custom textures or material
  9923. * to allow the laoders to instantiate them
  9924. */
  9925. Tools.RegisteredExternalClasses = {};
  9926. // Used in case of a texture loading problem
  9927. 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";
  9928. Tools._tmpFloatArray = new Float32Array(1);
  9929. Tools.PreprocessUrl = function (url) {
  9930. return url;
  9931. };
  9932. // Logs
  9933. Tools._NoneLogLevel = 0;
  9934. Tools._MessageLogLevel = 1;
  9935. Tools._WarningLogLevel = 2;
  9936. Tools._ErrorLogLevel = 4;
  9937. Tools._LogCache = "";
  9938. Tools.errorsCount = 0;
  9939. Tools.Log = Tools._LogEnabled;
  9940. Tools.Warn = Tools._WarnEnabled;
  9941. Tools.Error = Tools._ErrorEnabled;
  9942. // Performances
  9943. Tools._PerformanceNoneLogLevel = 0;
  9944. Tools._PerformanceUserMarkLogLevel = 1;
  9945. Tools._PerformanceConsoleLogLevel = 2;
  9946. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9947. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9948. return Tools;
  9949. }());
  9950. BABYLON.Tools = Tools;
  9951. /**
  9952. * This class is used to track a performance counter which is number based.
  9953. * The user has access to many properties which give statistics of different nature
  9954. *
  9955. * The implementer can track two kinds of Performance Counter: time and count
  9956. * 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.
  9957. * 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.
  9958. */
  9959. var PerfCounter = /** @class */ (function () {
  9960. function PerfCounter() {
  9961. this._startMonitoringTime = 0;
  9962. this._min = 0;
  9963. this._max = 0;
  9964. this._average = 0;
  9965. this._lastSecAverage = 0;
  9966. this._current = 0;
  9967. this._totalValueCount = 0;
  9968. this._totalAccumulated = 0;
  9969. this._lastSecAccumulated = 0;
  9970. this._lastSecTime = 0;
  9971. this._lastSecValueCount = 0;
  9972. }
  9973. Object.defineProperty(PerfCounter.prototype, "min", {
  9974. /**
  9975. * Returns the smallest value ever
  9976. */
  9977. get: function () {
  9978. return this._min;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(PerfCounter.prototype, "max", {
  9984. /**
  9985. * Returns the biggest value ever
  9986. */
  9987. get: function () {
  9988. return this._max;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(PerfCounter.prototype, "average", {
  9994. /**
  9995. * Returns the average value since the performance counter is running
  9996. */
  9997. get: function () {
  9998. return this._average;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10004. /**
  10005. * Returns the average value of the last second the counter was monitored
  10006. */
  10007. get: function () {
  10008. return this._lastSecAverage;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(PerfCounter.prototype, "current", {
  10014. /**
  10015. * Returns the current value
  10016. */
  10017. get: function () {
  10018. return this._current;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(PerfCounter.prototype, "total", {
  10024. get: function () {
  10025. return this._totalAccumulated;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(PerfCounter.prototype, "count", {
  10031. get: function () {
  10032. return this._totalValueCount;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. /**
  10038. * Call this method to start monitoring a new frame.
  10039. * 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.
  10040. */
  10041. PerfCounter.prototype.fetchNewFrame = function () {
  10042. this._totalValueCount++;
  10043. this._current = 0;
  10044. this._lastSecValueCount++;
  10045. };
  10046. /**
  10047. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10048. * @param newCount the count value to add to the monitored count
  10049. * @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.
  10050. */
  10051. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10052. if (!PerfCounter.Enabled) {
  10053. return;
  10054. }
  10055. this._current += newCount;
  10056. if (fetchResult) {
  10057. this._fetchResult();
  10058. }
  10059. };
  10060. /**
  10061. * Start monitoring this performance counter
  10062. */
  10063. PerfCounter.prototype.beginMonitoring = function () {
  10064. if (!PerfCounter.Enabled) {
  10065. return;
  10066. }
  10067. this._startMonitoringTime = Tools.Now;
  10068. };
  10069. /**
  10070. * Compute the time lapsed since the previous beginMonitoring() call.
  10071. * @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
  10072. */
  10073. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10074. if (newFrame === void 0) { newFrame = true; }
  10075. if (!PerfCounter.Enabled) {
  10076. return;
  10077. }
  10078. if (newFrame) {
  10079. this.fetchNewFrame();
  10080. }
  10081. var currentTime = Tools.Now;
  10082. this._current = currentTime - this._startMonitoringTime;
  10083. if (newFrame) {
  10084. this._fetchResult();
  10085. }
  10086. };
  10087. PerfCounter.prototype._fetchResult = function () {
  10088. this._totalAccumulated += this._current;
  10089. this._lastSecAccumulated += this._current;
  10090. // Min/Max update
  10091. this._min = Math.min(this._min, this._current);
  10092. this._max = Math.max(this._max, this._current);
  10093. this._average = this._totalAccumulated / this._totalValueCount;
  10094. // Reset last sec?
  10095. var now = Tools.Now;
  10096. if ((now - this._lastSecTime) > 1000) {
  10097. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10098. this._lastSecTime = now;
  10099. this._lastSecAccumulated = 0;
  10100. this._lastSecValueCount = 0;
  10101. }
  10102. };
  10103. PerfCounter.Enabled = true;
  10104. return PerfCounter;
  10105. }());
  10106. BABYLON.PerfCounter = PerfCounter;
  10107. /**
  10108. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10109. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10110. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10111. * @param name The name of the class, case should be preserved
  10112. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10113. */
  10114. function className(name, module) {
  10115. return function (target) {
  10116. target["__bjsclassName__"] = name;
  10117. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10118. };
  10119. }
  10120. BABYLON.className = className;
  10121. /**
  10122. * An implementation of a loop for asynchronous functions.
  10123. */
  10124. var AsyncLoop = /** @class */ (function () {
  10125. /**
  10126. * Constroctor.
  10127. * @param iterations the number of iterations.
  10128. * @param _fn the function to run each iteration
  10129. * @param _successCallback the callback that will be called upon succesful execution
  10130. * @param offset starting offset.
  10131. */
  10132. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10133. if (offset === void 0) { offset = 0; }
  10134. this.iterations = iterations;
  10135. this._fn = _fn;
  10136. this._successCallback = _successCallback;
  10137. this.index = offset - 1;
  10138. this._done = false;
  10139. }
  10140. /**
  10141. * Execute the next iteration. Must be called after the last iteration was finished.
  10142. */
  10143. AsyncLoop.prototype.executeNext = function () {
  10144. if (!this._done) {
  10145. if (this.index + 1 < this.iterations) {
  10146. ++this.index;
  10147. this._fn(this);
  10148. }
  10149. else {
  10150. this.breakLoop();
  10151. }
  10152. }
  10153. };
  10154. /**
  10155. * Break the loop and run the success callback.
  10156. */
  10157. AsyncLoop.prototype.breakLoop = function () {
  10158. this._done = true;
  10159. this._successCallback();
  10160. };
  10161. /**
  10162. * Helper function
  10163. */
  10164. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10165. if (offset === void 0) { offset = 0; }
  10166. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10167. loop.executeNext();
  10168. return loop;
  10169. };
  10170. /**
  10171. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10172. * @param iterations total number of iterations
  10173. * @param syncedIterations number of synchronous iterations in each async iteration.
  10174. * @param fn the function to call each iteration.
  10175. * @param callback a success call back that will be called when iterating stops.
  10176. * @param breakFunction a break condition (optional)
  10177. * @param timeout timeout settings for the setTimeout function. default - 0.
  10178. * @constructor
  10179. */
  10180. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10181. if (timeout === void 0) { timeout = 0; }
  10182. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10183. if (breakFunction && breakFunction())
  10184. loop.breakLoop();
  10185. else {
  10186. setTimeout(function () {
  10187. for (var i = 0; i < syncedIterations; ++i) {
  10188. var iteration = (loop.index * syncedIterations) + i;
  10189. if (iteration >= iterations)
  10190. break;
  10191. fn(iteration);
  10192. if (breakFunction && breakFunction()) {
  10193. loop.breakLoop();
  10194. break;
  10195. }
  10196. }
  10197. loop.executeNext();
  10198. }, timeout);
  10199. }
  10200. }, callback);
  10201. };
  10202. return AsyncLoop;
  10203. }());
  10204. BABYLON.AsyncLoop = AsyncLoop;
  10205. })(BABYLON || (BABYLON = {}));
  10206. //# sourceMappingURL=babylon.tools.js.map
  10207. var BABYLON;
  10208. (function (BABYLON) {
  10209. var PromiseStates;
  10210. (function (PromiseStates) {
  10211. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10212. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10213. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10214. })(PromiseStates || (PromiseStates = {}));
  10215. var FulFillmentAgregator = /** @class */ (function () {
  10216. function FulFillmentAgregator() {
  10217. this.count = 0;
  10218. this.target = 0;
  10219. this.results = [];
  10220. }
  10221. return FulFillmentAgregator;
  10222. }());
  10223. var InternalPromise = /** @class */ (function () {
  10224. function InternalPromise(resolver) {
  10225. var _this = this;
  10226. this._state = PromiseStates.Pending;
  10227. this._children = new Array();
  10228. this._rejectWasConsumed = false;
  10229. if (!resolver) {
  10230. return;
  10231. }
  10232. try {
  10233. resolver(function (value) {
  10234. _this._resolve(value);
  10235. }, function (reason) {
  10236. _this._reject(reason);
  10237. });
  10238. }
  10239. catch (e) {
  10240. this._reject(e);
  10241. }
  10242. }
  10243. Object.defineProperty(InternalPromise.prototype, "_result", {
  10244. get: function () {
  10245. return this._resultValue;
  10246. },
  10247. set: function (value) {
  10248. this._resultValue = value;
  10249. if (this._parent && this._parent._result === undefined) {
  10250. this._parent._result = value;
  10251. }
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. InternalPromise.prototype.catch = function (onRejected) {
  10257. return this.then(undefined, onRejected);
  10258. };
  10259. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10260. var _this = this;
  10261. var newPromise = new InternalPromise();
  10262. newPromise._onFulfilled = onFulfilled;
  10263. newPromise._onRejected = onRejected;
  10264. // Composition
  10265. this._children.push(newPromise);
  10266. newPromise._parent = this;
  10267. if (this._state !== PromiseStates.Pending) {
  10268. BABYLON.Tools.SetImmediate(function () {
  10269. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10270. var returnedValue = newPromise._resolve(_this._result);
  10271. if (returnedValue !== undefined && returnedValue !== null) {
  10272. if (returnedValue._state !== undefined) {
  10273. var returnedPromise = returnedValue;
  10274. newPromise._children.push(returnedPromise);
  10275. returnedPromise._parent = newPromise;
  10276. newPromise = returnedPromise;
  10277. }
  10278. else {
  10279. newPromise._result = returnedValue;
  10280. }
  10281. }
  10282. }
  10283. else {
  10284. newPromise._reject(_this._reason);
  10285. }
  10286. });
  10287. }
  10288. return newPromise;
  10289. };
  10290. InternalPromise.prototype._moveChildren = function (children) {
  10291. var _this = this;
  10292. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10293. this._children.forEach(function (child) {
  10294. child._parent = _this;
  10295. });
  10296. if (this._state === PromiseStates.Fulfilled) {
  10297. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10298. var child = _b[_i];
  10299. child._resolve(this._result);
  10300. }
  10301. }
  10302. else if (this._state === PromiseStates.Rejected) {
  10303. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10304. var child = _d[_c];
  10305. child._reject(this._reason);
  10306. }
  10307. }
  10308. var _a;
  10309. };
  10310. InternalPromise.prototype._resolve = function (value) {
  10311. try {
  10312. this._state = PromiseStates.Fulfilled;
  10313. var returnedValue = null;
  10314. if (this._onFulfilled) {
  10315. returnedValue = this._onFulfilled(value);
  10316. }
  10317. if (returnedValue !== undefined && returnedValue !== null) {
  10318. if (returnedValue._state !== undefined) {
  10319. // Transmit children
  10320. var returnedPromise = returnedValue;
  10321. returnedPromise._parent = this;
  10322. returnedPromise._moveChildren(this._children);
  10323. value = returnedPromise._result;
  10324. }
  10325. else {
  10326. value = returnedValue;
  10327. }
  10328. }
  10329. this._result = value;
  10330. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10331. var child = _a[_i];
  10332. child._resolve(value);
  10333. }
  10334. this._children.length = 0;
  10335. delete this._onFulfilled;
  10336. delete this._onRejected;
  10337. }
  10338. catch (e) {
  10339. this._reject(e, true);
  10340. }
  10341. };
  10342. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10343. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10344. this._state = PromiseStates.Rejected;
  10345. this._reason = reason;
  10346. if (this._onRejected && !onLocalThrow) {
  10347. try {
  10348. this._onRejected(reason);
  10349. this._rejectWasConsumed = true;
  10350. }
  10351. catch (e) {
  10352. reason = e;
  10353. }
  10354. }
  10355. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10356. var child = _a[_i];
  10357. if (this._rejectWasConsumed) {
  10358. child._resolve(null);
  10359. }
  10360. else {
  10361. child._reject(reason);
  10362. }
  10363. }
  10364. this._children.length = 0;
  10365. delete this._onFulfilled;
  10366. delete this._onRejected;
  10367. };
  10368. InternalPromise.resolve = function (value) {
  10369. var newPromise = new InternalPromise();
  10370. newPromise._resolve(value);
  10371. return newPromise;
  10372. };
  10373. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10374. promise.then(function (value) {
  10375. agregator.results[index] = value;
  10376. agregator.count++;
  10377. if (agregator.count === agregator.target) {
  10378. agregator.rootPromise._resolve(agregator.results);
  10379. }
  10380. return null;
  10381. }, function (reason) {
  10382. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10383. agregator.rootPromise._reject(reason);
  10384. }
  10385. });
  10386. };
  10387. InternalPromise.all = function (promises) {
  10388. var newPromise = new InternalPromise();
  10389. var agregator = new FulFillmentAgregator();
  10390. agregator.target = promises.length;
  10391. agregator.rootPromise = newPromise;
  10392. if (promises.length) {
  10393. for (var index = 0; index < promises.length; index++) {
  10394. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10395. }
  10396. }
  10397. else {
  10398. newPromise._resolve([]);
  10399. }
  10400. return newPromise;
  10401. };
  10402. InternalPromise.race = function (promises) {
  10403. var newPromise = new InternalPromise();
  10404. if (promises.length) {
  10405. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10406. var promise = promises_1[_i];
  10407. promise.then(function (value) {
  10408. if (newPromise) {
  10409. newPromise._resolve(value);
  10410. newPromise = null;
  10411. }
  10412. return null;
  10413. }, function (reason) {
  10414. if (newPromise) {
  10415. newPromise._reject(reason);
  10416. newPromise = null;
  10417. }
  10418. });
  10419. }
  10420. }
  10421. return newPromise;
  10422. };
  10423. return InternalPromise;
  10424. }());
  10425. /**
  10426. * Helper class that provides a small promise polyfill
  10427. */
  10428. var PromisePolyfill = /** @class */ (function () {
  10429. function PromisePolyfill() {
  10430. }
  10431. /**
  10432. * Static function used to check if the polyfill is required
  10433. * If this is the case then the function will inject the polyfill to window.Promise
  10434. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10435. */
  10436. PromisePolyfill.Apply = function (force) {
  10437. if (force === void 0) { force = false; }
  10438. if (force || typeof Promise === 'undefined') {
  10439. var root = window;
  10440. root.Promise = InternalPromise;
  10441. }
  10442. };
  10443. return PromisePolyfill;
  10444. }());
  10445. BABYLON.PromisePolyfill = PromisePolyfill;
  10446. })(BABYLON || (BABYLON = {}));
  10447. //# sourceMappingURL=babylon.promise.js.map
  10448. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10449. var BABYLON;
  10450. (function (BABYLON) {
  10451. /**
  10452. * Helper class to push actions to a pool of workers.
  10453. */
  10454. var WorkerPool = /** @class */ (function () {
  10455. /**
  10456. * Constructor
  10457. * @param workers Array of workers to use for actions
  10458. */
  10459. function WorkerPool(workers) {
  10460. this._pendingActions = new Array();
  10461. this._workerInfos = workers.map(function (worker) { return ({
  10462. worker: worker,
  10463. active: false
  10464. }); });
  10465. }
  10466. /**
  10467. * Terminates all workers and clears any pending actions.
  10468. */
  10469. WorkerPool.prototype.dispose = function () {
  10470. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10471. var workerInfo = _a[_i];
  10472. workerInfo.worker.terminate();
  10473. }
  10474. delete this._workerInfos;
  10475. delete this._pendingActions;
  10476. };
  10477. /**
  10478. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10479. * pended until a worker has completed its action.
  10480. * @param action The action to perform. Call onComplete when the action is complete.
  10481. */
  10482. WorkerPool.prototype.push = function (action) {
  10483. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10484. var workerInfo = _a[_i];
  10485. if (!workerInfo.active) {
  10486. this._execute(workerInfo, action);
  10487. return;
  10488. }
  10489. }
  10490. this._pendingActions.push(action);
  10491. };
  10492. WorkerPool.prototype._execute = function (workerInfo, action) {
  10493. var _this = this;
  10494. workerInfo.active = true;
  10495. action(workerInfo.worker, function () {
  10496. workerInfo.active = false;
  10497. var nextAction = _this._pendingActions.shift();
  10498. if (nextAction) {
  10499. _this._execute(workerInfo, nextAction);
  10500. }
  10501. });
  10502. };
  10503. return WorkerPool;
  10504. }());
  10505. BABYLON.WorkerPool = WorkerPool;
  10506. })(BABYLON || (BABYLON = {}));
  10507. //# sourceMappingURL=babylon.workerPool.js.map
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. /**
  10511. * @hidden
  10512. **/
  10513. var _AlphaState = /** @class */ (function () {
  10514. /**
  10515. * Initializes the state.
  10516. */
  10517. function _AlphaState() {
  10518. this._isAlphaBlendDirty = false;
  10519. this._isBlendFunctionParametersDirty = false;
  10520. this._isBlendEquationParametersDirty = false;
  10521. this._isBlendConstantsDirty = false;
  10522. this._alphaBlend = false;
  10523. this._blendFunctionParameters = new Array(4);
  10524. this._blendEquationParameters = new Array(2);
  10525. this._blendConstants = new Array(4);
  10526. this.reset();
  10527. }
  10528. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10529. get: function () {
  10530. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10536. get: function () {
  10537. return this._alphaBlend;
  10538. },
  10539. set: function (value) {
  10540. if (this._alphaBlend === value) {
  10541. return;
  10542. }
  10543. this._alphaBlend = value;
  10544. this._isAlphaBlendDirty = true;
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10550. if (this._blendConstants[0] === r &&
  10551. this._blendConstants[1] === g &&
  10552. this._blendConstants[2] === b &&
  10553. this._blendConstants[3] === a) {
  10554. return;
  10555. }
  10556. this._blendConstants[0] = r;
  10557. this._blendConstants[1] = g;
  10558. this._blendConstants[2] = b;
  10559. this._blendConstants[3] = a;
  10560. this._isBlendConstantsDirty = true;
  10561. };
  10562. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10563. if (this._blendFunctionParameters[0] === value0 &&
  10564. this._blendFunctionParameters[1] === value1 &&
  10565. this._blendFunctionParameters[2] === value2 &&
  10566. this._blendFunctionParameters[3] === value3) {
  10567. return;
  10568. }
  10569. this._blendFunctionParameters[0] = value0;
  10570. this._blendFunctionParameters[1] = value1;
  10571. this._blendFunctionParameters[2] = value2;
  10572. this._blendFunctionParameters[3] = value3;
  10573. this._isBlendFunctionParametersDirty = true;
  10574. };
  10575. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10576. if (this._blendEquationParameters[0] === rgb &&
  10577. this._blendEquationParameters[1] === alpha) {
  10578. return;
  10579. }
  10580. this._blendEquationParameters[0] = rgb;
  10581. this._blendEquationParameters[1] = alpha;
  10582. this._isBlendEquationParametersDirty = true;
  10583. };
  10584. _AlphaState.prototype.reset = function () {
  10585. this._alphaBlend = false;
  10586. this._blendFunctionParameters[0] = null;
  10587. this._blendFunctionParameters[1] = null;
  10588. this._blendFunctionParameters[2] = null;
  10589. this._blendFunctionParameters[3] = null;
  10590. this._blendEquationParameters[0] = null;
  10591. this._blendEquationParameters[1] = null;
  10592. this._blendConstants[0] = null;
  10593. this._blendConstants[1] = null;
  10594. this._blendConstants[2] = null;
  10595. this._blendConstants[3] = null;
  10596. this._isAlphaBlendDirty = true;
  10597. this._isBlendFunctionParametersDirty = false;
  10598. this._isBlendEquationParametersDirty = false;
  10599. this._isBlendConstantsDirty = false;
  10600. };
  10601. _AlphaState.prototype.apply = function (gl) {
  10602. if (!this.isDirty) {
  10603. return;
  10604. }
  10605. // Alpha blend
  10606. if (this._isAlphaBlendDirty) {
  10607. if (this._alphaBlend) {
  10608. gl.enable(gl.BLEND);
  10609. }
  10610. else {
  10611. gl.disable(gl.BLEND);
  10612. }
  10613. this._isAlphaBlendDirty = false;
  10614. }
  10615. // Alpha function
  10616. if (this._isBlendFunctionParametersDirty) {
  10617. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10618. this._isBlendFunctionParametersDirty = false;
  10619. }
  10620. // Alpha equation
  10621. if (this._isBlendEquationParametersDirty) {
  10622. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10623. this._isBlendEquationParametersDirty = false;
  10624. }
  10625. // Constants
  10626. if (this._isBlendConstantsDirty) {
  10627. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10628. this._isBlendConstantsDirty = false;
  10629. }
  10630. };
  10631. return _AlphaState;
  10632. }());
  10633. BABYLON._AlphaState = _AlphaState;
  10634. })(BABYLON || (BABYLON = {}));
  10635. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10636. var BABYLON;
  10637. (function (BABYLON) {
  10638. /**
  10639. * @hidden
  10640. **/
  10641. var _DepthCullingState = /** @class */ (function () {
  10642. /**
  10643. * Initializes the state.
  10644. */
  10645. function _DepthCullingState() {
  10646. this._isDepthTestDirty = false;
  10647. this._isDepthMaskDirty = false;
  10648. this._isDepthFuncDirty = false;
  10649. this._isCullFaceDirty = false;
  10650. this._isCullDirty = false;
  10651. this._isZOffsetDirty = false;
  10652. this._isFrontFaceDirty = false;
  10653. this.reset();
  10654. }
  10655. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10656. get: function () {
  10657. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10663. get: function () {
  10664. return this._zOffset;
  10665. },
  10666. set: function (value) {
  10667. if (this._zOffset === value) {
  10668. return;
  10669. }
  10670. this._zOffset = value;
  10671. this._isZOffsetDirty = true;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10677. get: function () {
  10678. return this._cullFace;
  10679. },
  10680. set: function (value) {
  10681. if (this._cullFace === value) {
  10682. return;
  10683. }
  10684. this._cullFace = value;
  10685. this._isCullFaceDirty = true;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10691. get: function () {
  10692. return this._cull;
  10693. },
  10694. set: function (value) {
  10695. if (this._cull === value) {
  10696. return;
  10697. }
  10698. this._cull = value;
  10699. this._isCullDirty = true;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10705. get: function () {
  10706. return this._depthFunc;
  10707. },
  10708. set: function (value) {
  10709. if (this._depthFunc === value) {
  10710. return;
  10711. }
  10712. this._depthFunc = value;
  10713. this._isDepthFuncDirty = true;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10719. get: function () {
  10720. return this._depthMask;
  10721. },
  10722. set: function (value) {
  10723. if (this._depthMask === value) {
  10724. return;
  10725. }
  10726. this._depthMask = value;
  10727. this._isDepthMaskDirty = true;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10733. get: function () {
  10734. return this._depthTest;
  10735. },
  10736. set: function (value) {
  10737. if (this._depthTest === value) {
  10738. return;
  10739. }
  10740. this._depthTest = value;
  10741. this._isDepthTestDirty = true;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10747. get: function () {
  10748. return this._frontFace;
  10749. },
  10750. set: function (value) {
  10751. if (this._frontFace === value) {
  10752. return;
  10753. }
  10754. this._frontFace = value;
  10755. this._isFrontFaceDirty = true;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. _DepthCullingState.prototype.reset = function () {
  10761. this._depthMask = true;
  10762. this._depthTest = true;
  10763. this._depthFunc = null;
  10764. this._cullFace = null;
  10765. this._cull = null;
  10766. this._zOffset = 0;
  10767. this._frontFace = null;
  10768. this._isDepthTestDirty = true;
  10769. this._isDepthMaskDirty = true;
  10770. this._isDepthFuncDirty = false;
  10771. this._isCullFaceDirty = false;
  10772. this._isCullDirty = false;
  10773. this._isZOffsetDirty = false;
  10774. this._isFrontFaceDirty = false;
  10775. };
  10776. _DepthCullingState.prototype.apply = function (gl) {
  10777. if (!this.isDirty) {
  10778. return;
  10779. }
  10780. // Cull
  10781. if (this._isCullDirty) {
  10782. if (this.cull) {
  10783. gl.enable(gl.CULL_FACE);
  10784. }
  10785. else {
  10786. gl.disable(gl.CULL_FACE);
  10787. }
  10788. this._isCullDirty = false;
  10789. }
  10790. // Cull face
  10791. if (this._isCullFaceDirty) {
  10792. gl.cullFace(this.cullFace);
  10793. this._isCullFaceDirty = false;
  10794. }
  10795. // Depth mask
  10796. if (this._isDepthMaskDirty) {
  10797. gl.depthMask(this.depthMask);
  10798. this._isDepthMaskDirty = false;
  10799. }
  10800. // Depth test
  10801. if (this._isDepthTestDirty) {
  10802. if (this.depthTest) {
  10803. gl.enable(gl.DEPTH_TEST);
  10804. }
  10805. else {
  10806. gl.disable(gl.DEPTH_TEST);
  10807. }
  10808. this._isDepthTestDirty = false;
  10809. }
  10810. // Depth func
  10811. if (this._isDepthFuncDirty) {
  10812. gl.depthFunc(this.depthFunc);
  10813. this._isDepthFuncDirty = false;
  10814. }
  10815. // zOffset
  10816. if (this._isZOffsetDirty) {
  10817. if (this.zOffset) {
  10818. gl.enable(gl.POLYGON_OFFSET_FILL);
  10819. gl.polygonOffset(this.zOffset, 0);
  10820. }
  10821. else {
  10822. gl.disable(gl.POLYGON_OFFSET_FILL);
  10823. }
  10824. this._isZOffsetDirty = false;
  10825. }
  10826. // Front face
  10827. if (this._isFrontFaceDirty) {
  10828. gl.frontFace(this.frontFace);
  10829. this._isFrontFaceDirty = false;
  10830. }
  10831. };
  10832. return _DepthCullingState;
  10833. }());
  10834. BABYLON._DepthCullingState = _DepthCullingState;
  10835. })(BABYLON || (BABYLON = {}));
  10836. //# sourceMappingURL=babylon.depthCullingState.js.map
  10837. var BABYLON;
  10838. (function (BABYLON) {
  10839. /**
  10840. * @hidden
  10841. **/
  10842. var _StencilState = /** @class */ (function () {
  10843. function _StencilState() {
  10844. this._isStencilTestDirty = false;
  10845. this._isStencilMaskDirty = false;
  10846. this._isStencilFuncDirty = false;
  10847. this._isStencilOpDirty = false;
  10848. this.reset();
  10849. }
  10850. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10851. get: function () {
  10852. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10858. get: function () {
  10859. return this._stencilFunc;
  10860. },
  10861. set: function (value) {
  10862. if (this._stencilFunc === value) {
  10863. return;
  10864. }
  10865. this._stencilFunc = value;
  10866. this._isStencilFuncDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10872. get: function () {
  10873. return this._stencilFuncRef;
  10874. },
  10875. set: function (value) {
  10876. if (this._stencilFuncRef === value) {
  10877. return;
  10878. }
  10879. this._stencilFuncRef = value;
  10880. this._isStencilFuncDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10886. get: function () {
  10887. return this._stencilFuncMask;
  10888. },
  10889. set: function (value) {
  10890. if (this._stencilFuncMask === value) {
  10891. return;
  10892. }
  10893. this._stencilFuncMask = value;
  10894. this._isStencilFuncDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10900. get: function () {
  10901. return this._stencilOpStencilFail;
  10902. },
  10903. set: function (value) {
  10904. if (this._stencilOpStencilFail === value) {
  10905. return;
  10906. }
  10907. this._stencilOpStencilFail = value;
  10908. this._isStencilOpDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10914. get: function () {
  10915. return this._stencilOpDepthFail;
  10916. },
  10917. set: function (value) {
  10918. if (this._stencilOpDepthFail === value) {
  10919. return;
  10920. }
  10921. this._stencilOpDepthFail = value;
  10922. this._isStencilOpDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10928. get: function () {
  10929. return this._stencilOpStencilDepthPass;
  10930. },
  10931. set: function (value) {
  10932. if (this._stencilOpStencilDepthPass === value) {
  10933. return;
  10934. }
  10935. this._stencilOpStencilDepthPass = value;
  10936. this._isStencilOpDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10942. get: function () {
  10943. return this._stencilMask;
  10944. },
  10945. set: function (value) {
  10946. if (this._stencilMask === value) {
  10947. return;
  10948. }
  10949. this._stencilMask = value;
  10950. this._isStencilMaskDirty = true;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10956. get: function () {
  10957. return this._stencilTest;
  10958. },
  10959. set: function (value) {
  10960. if (this._stencilTest === value) {
  10961. return;
  10962. }
  10963. this._stencilTest = value;
  10964. this._isStencilTestDirty = true;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. _StencilState.prototype.reset = function () {
  10970. this._stencilTest = false;
  10971. this._stencilMask = 0xFF;
  10972. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10973. this._stencilFuncRef = 1;
  10974. this._stencilFuncMask = 0xFF;
  10975. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10976. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10977. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10978. this._isStencilTestDirty = true;
  10979. this._isStencilMaskDirty = true;
  10980. this._isStencilFuncDirty = true;
  10981. this._isStencilOpDirty = true;
  10982. };
  10983. _StencilState.prototype.apply = function (gl) {
  10984. if (!this.isDirty) {
  10985. return;
  10986. }
  10987. // Stencil test
  10988. if (this._isStencilTestDirty) {
  10989. if (this.stencilTest) {
  10990. gl.enable(gl.STENCIL_TEST);
  10991. }
  10992. else {
  10993. gl.disable(gl.STENCIL_TEST);
  10994. }
  10995. this._isStencilTestDirty = false;
  10996. }
  10997. // Stencil mask
  10998. if (this._isStencilMaskDirty) {
  10999. gl.stencilMask(this.stencilMask);
  11000. this._isStencilMaskDirty = false;
  11001. }
  11002. // Stencil func
  11003. if (this._isStencilFuncDirty) {
  11004. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11005. this._isStencilFuncDirty = false;
  11006. }
  11007. // Stencil op
  11008. if (this._isStencilOpDirty) {
  11009. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11010. this._isStencilOpDirty = false;
  11011. }
  11012. };
  11013. return _StencilState;
  11014. }());
  11015. BABYLON._StencilState = _StencilState;
  11016. })(BABYLON || (BABYLON = {}));
  11017. //# sourceMappingURL=babylon.stencilState.js.map
  11018. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11019. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11020. s = arguments[i];
  11021. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11022. t[p] = s[p];
  11023. }
  11024. return t;
  11025. };
  11026. var BABYLON;
  11027. (function (BABYLON) {
  11028. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11029. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11030. };
  11031. var compileRawShader = function (gl, source, type) {
  11032. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11033. gl.shaderSource(shader, source);
  11034. gl.compileShader(shader);
  11035. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11036. var log = gl.getShaderInfoLog(shader);
  11037. if (log) {
  11038. throw new Error(log);
  11039. }
  11040. }
  11041. if (!shader) {
  11042. throw new Error("Something went wrong while compile the shader.");
  11043. }
  11044. return shader;
  11045. };
  11046. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11047. var magFilter = gl.NEAREST;
  11048. var minFilter = gl.NEAREST;
  11049. switch (samplingMode) {
  11050. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11051. magFilter = gl.LINEAR;
  11052. if (generateMipMaps) {
  11053. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11054. }
  11055. else {
  11056. minFilter = gl.LINEAR;
  11057. }
  11058. break;
  11059. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11060. magFilter = gl.LINEAR;
  11061. if (generateMipMaps) {
  11062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11063. }
  11064. else {
  11065. minFilter = gl.LINEAR;
  11066. }
  11067. break;
  11068. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11069. magFilter = gl.NEAREST;
  11070. if (generateMipMaps) {
  11071. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11072. }
  11073. else {
  11074. minFilter = gl.NEAREST;
  11075. }
  11076. break;
  11077. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11078. magFilter = gl.NEAREST;
  11079. if (generateMipMaps) {
  11080. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11081. }
  11082. else {
  11083. minFilter = gl.NEAREST;
  11084. }
  11085. break;
  11086. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11087. magFilter = gl.NEAREST;
  11088. if (generateMipMaps) {
  11089. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11090. }
  11091. else {
  11092. minFilter = gl.LINEAR;
  11093. }
  11094. break;
  11095. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11096. magFilter = gl.NEAREST;
  11097. if (generateMipMaps) {
  11098. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11099. }
  11100. else {
  11101. minFilter = gl.LINEAR;
  11102. }
  11103. break;
  11104. case BABYLON.Texture.NEAREST_LINEAR:
  11105. magFilter = gl.NEAREST;
  11106. minFilter = gl.LINEAR;
  11107. break;
  11108. case BABYLON.Texture.NEAREST_NEAREST:
  11109. magFilter = gl.NEAREST;
  11110. minFilter = gl.NEAREST;
  11111. break;
  11112. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11113. magFilter = gl.LINEAR;
  11114. if (generateMipMaps) {
  11115. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11116. }
  11117. else {
  11118. minFilter = gl.NEAREST;
  11119. }
  11120. break;
  11121. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11122. magFilter = gl.LINEAR;
  11123. if (generateMipMaps) {
  11124. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11125. }
  11126. else {
  11127. minFilter = gl.NEAREST;
  11128. }
  11129. break;
  11130. case BABYLON.Texture.LINEAR_LINEAR:
  11131. magFilter = gl.LINEAR;
  11132. minFilter = gl.LINEAR;
  11133. break;
  11134. case BABYLON.Texture.LINEAR_NEAREST:
  11135. magFilter = gl.LINEAR;
  11136. minFilter = gl.NEAREST;
  11137. break;
  11138. }
  11139. return {
  11140. min: minFilter,
  11141. mag: magFilter
  11142. };
  11143. };
  11144. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11145. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11146. var img;
  11147. var onload = function () {
  11148. loadedImages[index] = img;
  11149. loadedImages._internalCount++;
  11150. if (scene) {
  11151. scene._removePendingData(img);
  11152. }
  11153. if (loadedImages._internalCount === 6) {
  11154. onfinish(loadedImages);
  11155. }
  11156. };
  11157. var onerror = function (message, exception) {
  11158. if (scene) {
  11159. scene._removePendingData(img);
  11160. }
  11161. if (onErrorCallBack) {
  11162. onErrorCallBack(message, exception);
  11163. }
  11164. };
  11165. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11166. if (scene) {
  11167. scene._addPendingData(img);
  11168. }
  11169. };
  11170. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11171. if (onError === void 0) { onError = null; }
  11172. var loadedImages = [];
  11173. loadedImages._internalCount = 0;
  11174. for (var index = 0; index < 6; index++) {
  11175. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11176. }
  11177. };
  11178. var BufferPointer = /** @class */ (function () {
  11179. function BufferPointer() {
  11180. }
  11181. return BufferPointer;
  11182. }());
  11183. /**
  11184. * Interface for attribute information associated with buffer instanciation
  11185. */
  11186. var InstancingAttributeInfo = /** @class */ (function () {
  11187. function InstancingAttributeInfo() {
  11188. }
  11189. return InstancingAttributeInfo;
  11190. }());
  11191. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11192. /**
  11193. * Define options used to create a render target texture
  11194. */
  11195. var RenderTargetCreationOptions = /** @class */ (function () {
  11196. function RenderTargetCreationOptions() {
  11197. }
  11198. return RenderTargetCreationOptions;
  11199. }());
  11200. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11201. /**
  11202. * Define options used to create a depth texture
  11203. */
  11204. var DepthTextureCreationOptions = /** @class */ (function () {
  11205. function DepthTextureCreationOptions() {
  11206. }
  11207. return DepthTextureCreationOptions;
  11208. }());
  11209. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11210. /**
  11211. * Class used to describe the capabilities of the engine relatively to the current browser
  11212. */
  11213. var EngineCapabilities = /** @class */ (function () {
  11214. function EngineCapabilities() {
  11215. }
  11216. return EngineCapabilities;
  11217. }());
  11218. BABYLON.EngineCapabilities = EngineCapabilities;
  11219. /**
  11220. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11221. */
  11222. var Engine = /** @class */ (function () {
  11223. /**
  11224. * Creates a new engine
  11225. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11226. * @param antialias defines enable antialiasing (default: false)
  11227. * @param options defines further options to be sent to the getContext() function
  11228. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11229. */
  11230. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11231. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11232. var _this = this;
  11233. // Public members
  11234. /**
  11235. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11236. */
  11237. this.forcePOTTextures = false;
  11238. /**
  11239. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11240. */
  11241. this.isFullscreen = false;
  11242. /**
  11243. * Gets a boolean indicating if the pointer is currently locked
  11244. */
  11245. this.isPointerLock = false;
  11246. /**
  11247. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11248. */
  11249. this.cullBackFaces = true;
  11250. /**
  11251. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11252. */
  11253. this.renderEvenInBackground = true;
  11254. /**
  11255. * Gets or sets a boolean indicating that cache can be kept between frames
  11256. */
  11257. this.preventCacheWipeBetweenFrames = false;
  11258. /**
  11259. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11260. **/
  11261. this.enableOfflineSupport = false;
  11262. /**
  11263. * 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)
  11264. **/
  11265. this.disableManifestCheck = false;
  11266. /**
  11267. * Gets the list of created scenes
  11268. */
  11269. this.scenes = new Array();
  11270. /**
  11271. * Gets the list of created postprocesses
  11272. */
  11273. this.postProcesses = new Array();
  11274. // Observables
  11275. /**
  11276. * Observable event triggered each time the rendering canvas is resized
  11277. */
  11278. this.onResizeObservable = new BABYLON.Observable();
  11279. /**
  11280. * Observable event triggered each time the canvas loses focus
  11281. */
  11282. this.onCanvasBlurObservable = new BABYLON.Observable();
  11283. /**
  11284. * Observable event triggered each time the canvas gains focus
  11285. */
  11286. this.onCanvasFocusObservable = new BABYLON.Observable();
  11287. /**
  11288. * Observable event triggered each time the canvas receives pointerout event
  11289. */
  11290. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable event triggered before each texture is initialized
  11293. */
  11294. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11295. //WebVR
  11296. this._vrDisplay = undefined;
  11297. this._vrSupported = false;
  11298. this._vrExclusivePointerMode = false;
  11299. // Uniform buffers list
  11300. /**
  11301. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11302. */
  11303. this.disableUniformBuffers = false;
  11304. /** @hidden */
  11305. this._uniformBuffers = new Array();
  11306. // Observables
  11307. /**
  11308. * Observable raised when the engine begins a new frame
  11309. */
  11310. this.onBeginFrameObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable raised when the engine ends the current frame
  11313. */
  11314. this.onEndFrameObservable = new BABYLON.Observable();
  11315. /**
  11316. * Observable raised when the engine is about to compile a shader
  11317. */
  11318. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11319. /**
  11320. * Observable raised when the engine has jsut compiled a shader
  11321. */
  11322. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11323. this._windowIsBackground = false;
  11324. this._webGLVersion = 1.0;
  11325. /** @hidden */
  11326. this._badOS = false;
  11327. /** @hidden */
  11328. this._badDesktopOS = false;
  11329. /**
  11330. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11331. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11332. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11333. */
  11334. this.disableTextureBindingOptimization = false;
  11335. /**
  11336. * Observable signaled when VR display mode changes
  11337. */
  11338. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11339. /**
  11340. * Observable signaled when VR request present is complete
  11341. */
  11342. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11343. /**
  11344. * Observable signaled when VR request present starts
  11345. */
  11346. this.onVRRequestPresentStart = new BABYLON.Observable();
  11347. this._colorWrite = true;
  11348. /** @hidden */
  11349. this._drawCalls = new BABYLON.PerfCounter();
  11350. /** @hidden */
  11351. this._textureCollisions = new BABYLON.PerfCounter();
  11352. this._renderingQueueLaunched = false;
  11353. this._activeRenderLoops = new Array();
  11354. // Deterministic lockstepMaxSteps
  11355. this._deterministicLockstep = false;
  11356. this._lockstepMaxSteps = 4;
  11357. // Lost context
  11358. /**
  11359. * Observable signaled when a context lost event is raised
  11360. */
  11361. this.onContextLostObservable = new BABYLON.Observable();
  11362. /**
  11363. * Observable signaled when a context restored event is raised
  11364. */
  11365. this.onContextRestoredObservable = new BABYLON.Observable();
  11366. this._contextWasLost = false;
  11367. this._doNotHandleContextLost = false;
  11368. // FPS
  11369. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11370. this._fps = 60;
  11371. this._deltaTime = 0;
  11372. /**
  11373. * Turn this value on if you want to pause FPS computation when in background
  11374. */
  11375. this.disablePerformanceMonitorInBackground = false;
  11376. // States
  11377. /** @hidden */
  11378. this._depthCullingState = new BABYLON._DepthCullingState();
  11379. /** @hidden */
  11380. this._stencilState = new BABYLON._StencilState();
  11381. /** @hidden */
  11382. this._alphaState = new BABYLON._AlphaState();
  11383. /** @hidden */
  11384. this._alphaMode = Engine.ALPHA_DISABLE;
  11385. // Cache
  11386. this._internalTexturesCache = new Array();
  11387. /** @hidden */
  11388. this._activeChannel = 0;
  11389. this._currentTextureChannel = -1;
  11390. /** @hidden */
  11391. this._boundTexturesCache = {};
  11392. this._compiledEffects = {};
  11393. this._vertexAttribArraysEnabled = [];
  11394. this._uintIndicesCurrentlySet = false;
  11395. this._currentBoundBuffer = new Array();
  11396. this._currentBufferPointers = new Array();
  11397. this._currentInstanceLocations = new Array();
  11398. this._currentInstanceBuffers = new Array();
  11399. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11400. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11401. this._vaoRecordInProgress = false;
  11402. this._mustWipeVertexAttributes = false;
  11403. this._nextFreeTextureSlots = new Array();
  11404. this._maxSimultaneousTextures = 0;
  11405. this._activeRequests = new Array();
  11406. // Hardware supported Compressed Textures
  11407. this._texturesSupported = new Array();
  11408. /**
  11409. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11410. */
  11411. this.premultipliedAlpha = true;
  11412. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11413. this._onVRFullScreenTriggered = function () {
  11414. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11415. //get the old size before we change
  11416. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11417. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11418. //get the width and height, change the render size
  11419. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11420. _this.setHardwareScalingLevel(1);
  11421. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11422. }
  11423. else {
  11424. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11425. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11426. }
  11427. };
  11428. this._unpackFlipYCached = null;
  11429. this._boundUniforms = {};
  11430. // Register promises
  11431. BABYLON.PromisePolyfill.Apply();
  11432. var canvas = null;
  11433. Engine.Instances.push(this);
  11434. if (!canvasOrContext) {
  11435. return;
  11436. }
  11437. options = options || {};
  11438. if (canvasOrContext.getContext) {
  11439. canvas = canvasOrContext;
  11440. this._renderingCanvas = canvas;
  11441. if (antialias != null) {
  11442. options.antialias = antialias;
  11443. }
  11444. if (options.deterministicLockstep === undefined) {
  11445. options.deterministicLockstep = false;
  11446. }
  11447. if (options.lockstepMaxSteps === undefined) {
  11448. options.lockstepMaxSteps = 4;
  11449. }
  11450. if (options.preserveDrawingBuffer === undefined) {
  11451. options.preserveDrawingBuffer = false;
  11452. }
  11453. if (options.audioEngine === undefined) {
  11454. options.audioEngine = true;
  11455. }
  11456. if (options.stencil === undefined) {
  11457. options.stencil = true;
  11458. }
  11459. if (options.premultipliedAlpha === false) {
  11460. this.premultipliedAlpha = false;
  11461. }
  11462. this._deterministicLockstep = options.deterministicLockstep;
  11463. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11464. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11465. // Exceptions
  11466. if (navigator && navigator.userAgent) {
  11467. var ua = navigator.userAgent;
  11468. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11469. var exception = _a[_i];
  11470. var key = exception.key;
  11471. var targets = exception.targets;
  11472. if (ua.indexOf(key) > -1) {
  11473. if (exception.capture && exception.captureConstraint) {
  11474. var capture = exception.capture;
  11475. var constraint = exception.captureConstraint;
  11476. var regex = new RegExp(capture);
  11477. var matches = regex.exec(ua);
  11478. if (matches && matches.length > 0) {
  11479. var capturedValue = parseInt(matches[matches.length - 1]);
  11480. if (capturedValue >= constraint) {
  11481. continue;
  11482. }
  11483. }
  11484. }
  11485. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11486. var target = targets_1[_b];
  11487. switch (target) {
  11488. case "uniformBuffer":
  11489. this.disableUniformBuffers = true;
  11490. break;
  11491. case "textureBindingOptimization":
  11492. this.disableTextureBindingOptimization = true;
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. }
  11499. // GL
  11500. if (!options.disableWebGL2Support) {
  11501. try {
  11502. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11503. if (this._gl) {
  11504. this._webGLVersion = 2.0;
  11505. }
  11506. }
  11507. catch (e) {
  11508. // Do nothing
  11509. }
  11510. }
  11511. if (!this._gl) {
  11512. if (!canvas) {
  11513. throw new Error("The provided canvas is null or undefined.");
  11514. }
  11515. try {
  11516. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11517. }
  11518. catch (e) {
  11519. throw new Error("WebGL not supported");
  11520. }
  11521. }
  11522. if (!this._gl) {
  11523. throw new Error("WebGL not supported");
  11524. }
  11525. this._onCanvasFocus = function () {
  11526. _this.onCanvasFocusObservable.notifyObservers(_this);
  11527. };
  11528. this._onCanvasBlur = function () {
  11529. _this.onCanvasBlurObservable.notifyObservers(_this);
  11530. };
  11531. canvas.addEventListener("focus", this._onCanvasFocus);
  11532. canvas.addEventListener("blur", this._onCanvasBlur);
  11533. this._onBlur = function () {
  11534. if (_this.disablePerformanceMonitorInBackground) {
  11535. _this._performanceMonitor.disable();
  11536. }
  11537. _this._windowIsBackground = true;
  11538. };
  11539. this._onFocus = function () {
  11540. if (_this.disablePerformanceMonitorInBackground) {
  11541. _this._performanceMonitor.enable();
  11542. }
  11543. _this._windowIsBackground = false;
  11544. };
  11545. this._onCanvasPointerOut = function (ev) {
  11546. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11547. };
  11548. window.addEventListener("blur", this._onBlur);
  11549. window.addEventListener("focus", this._onFocus);
  11550. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11551. // Context lost
  11552. if (!this._doNotHandleContextLost) {
  11553. this._onContextLost = function (evt) {
  11554. evt.preventDefault();
  11555. _this._contextWasLost = true;
  11556. BABYLON.Tools.Warn("WebGL context lost.");
  11557. _this.onContextLostObservable.notifyObservers(_this);
  11558. };
  11559. this._onContextRestored = function (evt) {
  11560. // Adding a timeout to avoid race condition at browser level
  11561. setTimeout(function () {
  11562. // Rebuild gl context
  11563. _this._initGLContext();
  11564. // Rebuild effects
  11565. _this._rebuildEffects();
  11566. // Rebuild textures
  11567. _this._rebuildInternalTextures();
  11568. // Rebuild buffers
  11569. _this._rebuildBuffers();
  11570. // Cache
  11571. _this.wipeCaches(true);
  11572. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11573. _this.onContextRestoredObservable.notifyObservers(_this);
  11574. _this._contextWasLost = false;
  11575. }, 0);
  11576. };
  11577. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11578. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11579. }
  11580. }
  11581. else {
  11582. this._gl = canvasOrContext;
  11583. this._renderingCanvas = this._gl.canvas;
  11584. if (this._gl.renderbufferStorageMultisample) {
  11585. this._webGLVersion = 2.0;
  11586. }
  11587. options.stencil = this._gl.getContextAttributes().stencil;
  11588. }
  11589. // Viewport
  11590. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11591. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11592. this.resize();
  11593. this._isStencilEnable = options.stencil ? true : false;
  11594. this._initGLContext();
  11595. if (canvas) {
  11596. // Fullscreen
  11597. this._onFullscreenChange = function () {
  11598. if (document.fullscreen !== undefined) {
  11599. _this.isFullscreen = document.fullscreen;
  11600. }
  11601. else if (document.mozFullScreen !== undefined) {
  11602. _this.isFullscreen = document.mozFullScreen;
  11603. }
  11604. else if (document.webkitIsFullScreen !== undefined) {
  11605. _this.isFullscreen = document.webkitIsFullScreen;
  11606. }
  11607. else if (document.msIsFullScreen !== undefined) {
  11608. _this.isFullscreen = document.msIsFullScreen;
  11609. }
  11610. // Pointer lock
  11611. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11612. canvas.requestPointerLock = canvas.requestPointerLock ||
  11613. canvas.msRequestPointerLock ||
  11614. canvas.mozRequestPointerLock ||
  11615. canvas.webkitRequestPointerLock;
  11616. if (canvas.requestPointerLock) {
  11617. canvas.requestPointerLock();
  11618. }
  11619. }
  11620. };
  11621. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11622. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11623. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11624. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11625. // Pointer lock
  11626. this._onPointerLockChange = function () {
  11627. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11628. document.webkitPointerLockElement === canvas ||
  11629. document.msPointerLockElement === canvas ||
  11630. document.pointerLockElement === canvas);
  11631. };
  11632. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11633. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11634. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11635. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11636. this._onVRDisplayPointerRestricted = function () {
  11637. if (canvas) {
  11638. canvas.requestPointerLock();
  11639. }
  11640. };
  11641. this._onVRDisplayPointerUnrestricted = function () {
  11642. document.exitPointerLock();
  11643. };
  11644. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11645. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11646. }
  11647. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11648. Engine.audioEngine = new BABYLON.AudioEngine();
  11649. }
  11650. // Prepare buffer pointers
  11651. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11652. this._currentBufferPointers[i] = new BufferPointer();
  11653. }
  11654. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11655. // Load WebVR Devices
  11656. if (options.autoEnableWebVR) {
  11657. this.initWebVR();
  11658. }
  11659. // Detect if we are running on a faulty buggy OS.
  11660. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11661. // Detect if we are running on a faulty buggy desktop OS.
  11662. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11663. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11664. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11665. }
  11666. Object.defineProperty(Engine, "LastCreatedEngine", {
  11667. /**
  11668. * Gets the latest created engine
  11669. */
  11670. get: function () {
  11671. if (Engine.Instances.length === 0) {
  11672. return null;
  11673. }
  11674. return Engine.Instances[Engine.Instances.length - 1];
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "LastCreatedScene", {
  11680. /**
  11681. * Gets the latest created scene
  11682. */
  11683. get: function () {
  11684. var lastCreatedEngine = Engine.LastCreatedEngine;
  11685. if (!lastCreatedEngine) {
  11686. return null;
  11687. }
  11688. if (lastCreatedEngine.scenes.length === 0) {
  11689. return null;
  11690. }
  11691. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. /**
  11697. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11698. * @param flag defines which part of the materials must be marked as dirty
  11699. * @param predicate defines a predicate used to filter which materials should be affected
  11700. */
  11701. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11702. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11703. var engine = Engine.Instances[engineIndex];
  11704. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11705. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11706. }
  11707. }
  11708. };
  11709. Object.defineProperty(Engine, "NEVER", {
  11710. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11711. get: function () {
  11712. return Engine._NEVER;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "ALWAYS", {
  11718. /** 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 */
  11719. get: function () {
  11720. return Engine._ALWAYS;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "LESS", {
  11726. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11727. get: function () {
  11728. return Engine._LESS;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "EQUAL", {
  11734. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11735. get: function () {
  11736. return Engine._EQUAL;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "LEQUAL", {
  11742. /** 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 */
  11743. get: function () {
  11744. return Engine._LEQUAL;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "GREATER", {
  11750. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11751. get: function () {
  11752. return Engine._GREATER;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "GEQUAL", {
  11758. /** 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 */
  11759. get: function () {
  11760. return Engine._GEQUAL;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "NOTEQUAL", {
  11766. /** 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 */
  11767. get: function () {
  11768. return Engine._NOTEQUAL;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "KEEP", {
  11774. /** Passed to stencilOperation to specify that stencil value must be kept */
  11775. get: function () {
  11776. return Engine._KEEP;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "REPLACE", {
  11782. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11783. get: function () {
  11784. return Engine._REPLACE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "INCR", {
  11790. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11791. get: function () {
  11792. return Engine._INCR;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "DECR", {
  11798. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11799. get: function () {
  11800. return Engine._DECR;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "INVERT", {
  11806. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11807. get: function () {
  11808. return Engine._INVERT;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "INCR_WRAP", {
  11814. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11815. get: function () {
  11816. return Engine._INCR_WRAP;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "DECR_WRAP", {
  11822. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11823. get: function () {
  11824. return Engine._DECR_WRAP;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11830. // Alpha
  11831. /** Defines that alpha blending is disabled */
  11832. get: function () {
  11833. return Engine._ALPHA_DISABLE;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11839. /** Defines that alpha blending to SRC + DEST */
  11840. get: function () {
  11841. return Engine._ALPHA_ONEONE;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(Engine, "ALPHA_ADD", {
  11847. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11848. get: function () {
  11849. return Engine._ALPHA_ADD;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11855. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11856. get: function () {
  11857. return Engine._ALPHA_COMBINE;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11863. /** Defines that alpha blending to DEST - SRC * DEST */
  11864. get: function () {
  11865. return Engine._ALPHA_SUBTRACT;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11871. /** Defines that alpha blending to SRC * DEST */
  11872. get: function () {
  11873. return Engine._ALPHA_MULTIPLY;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11879. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11880. get: function () {
  11881. return Engine._ALPHA_MAXIMIZED;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11887. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11888. get: function () {
  11889. return Engine._ALPHA_PREMULTIPLIED;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11895. /**
  11896. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11897. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11898. */
  11899. get: function () {
  11900. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11906. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11907. get: function () {
  11908. return Engine._ALPHA_INTERPOLATE;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11914. /**
  11915. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11916. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11917. */
  11918. get: function () {
  11919. return Engine._ALPHA_SCREENMODE;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11925. // Delays
  11926. /** Defines that the ressource is not delayed*/
  11927. get: function () {
  11928. return Engine._DELAYLOADSTATE_NONE;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11934. /** Defines that the ressource was successfully delay loaded */
  11935. get: function () {
  11936. return Engine._DELAYLOADSTATE_LOADED;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11942. /** Defines that the ressource is currently delay loading */
  11943. get: function () {
  11944. return Engine._DELAYLOADSTATE_LOADING;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11950. /** Defines that the ressource is delayed and has not started loading */
  11951. get: function () {
  11952. return Engine._DELAYLOADSTATE_NOTLOADED;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11958. /** ALPHA */
  11959. get: function () {
  11960. return Engine._TEXTUREFORMAT_ALPHA;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11966. /** LUMINANCE */
  11967. get: function () {
  11968. return Engine._TEXTUREFORMAT_LUMINANCE;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11974. /**
  11975. * R
  11976. */
  11977. get: function () {
  11978. return Engine._TEXTUREFORMAT_R;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11984. /**
  11985. * RG
  11986. */
  11987. get: function () {
  11988. return Engine._TEXTUREFORMAT_RG;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11994. /** LUMINANCE_ALPHA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12002. /** RGB */
  12003. get: function () {
  12004. return Engine._TEXTUREFORMAT_RGB;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12010. /** RGBA */
  12011. get: function () {
  12012. return Engine._TEXTUREFORMAT_RGBA;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12018. /** UNSIGNED_INT */
  12019. get: function () {
  12020. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12026. /** FLOAT */
  12027. get: function () {
  12028. return Engine._TEXTURETYPE_FLOAT;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12034. /** HALF_FLOAT */
  12035. get: function () {
  12036. return Engine._TEXTURETYPE_HALF_FLOAT;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12042. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12043. get: function () {
  12044. return Engine._SCALEMODE_FLOOR;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12050. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12051. get: function () {
  12052. return Engine._SCALEMODE_NEAREST;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12058. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12059. get: function () {
  12060. return Engine._SCALEMODE_CEILING;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Engine, "Version", {
  12066. /**
  12067. * Returns the current version of the framework
  12068. */
  12069. get: function () {
  12070. return "3.3.0-alpha.8";
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12076. /**
  12077. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12078. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12079. */
  12080. get: function () {
  12081. return this._vrExclusivePointerMode;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12087. /**
  12088. * Gets a boolean indicating that the engine supports uniform buffers
  12089. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12090. */
  12091. get: function () {
  12092. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12098. /**
  12099. * Gets a boolean indicating that only power of 2 textures are supported
  12100. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12101. */
  12102. get: function () {
  12103. return this._webGLVersion < 2 || this.forcePOTTextures;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12109. /**
  12110. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12111. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12112. */
  12113. get: function () {
  12114. return this._doNotHandleContextLost;
  12115. },
  12116. set: function (value) {
  12117. this._doNotHandleContextLost = value;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12123. /**
  12124. * Gets the performance monitor attached to this engine
  12125. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12126. */
  12127. get: function () {
  12128. return this._performanceMonitor;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12134. /**
  12135. * Gets the list of texture formats supported
  12136. */
  12137. get: function () {
  12138. return this._texturesSupported;
  12139. },
  12140. enumerable: true,
  12141. configurable: true
  12142. });
  12143. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12144. /**
  12145. * Gets the list of texture formats in use
  12146. */
  12147. get: function () {
  12148. return this._textureFormatInUse;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Engine.prototype, "currentViewport", {
  12154. /**
  12155. * Gets the current viewport
  12156. */
  12157. get: function () {
  12158. return this._cachedViewport;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12164. /**
  12165. * Gets the default empty texture
  12166. */
  12167. get: function () {
  12168. if (!this._emptyTexture) {
  12169. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12170. }
  12171. return this._emptyTexture;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12177. /**
  12178. * Gets the default empty 3D texture
  12179. */
  12180. get: function () {
  12181. if (!this._emptyTexture3D) {
  12182. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12183. }
  12184. return this._emptyTexture3D;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12190. /**
  12191. * Gets the default empty cube texture
  12192. */
  12193. get: function () {
  12194. if (!this._emptyCubeTexture) {
  12195. var faceData = new Uint8Array(4);
  12196. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12197. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12198. }
  12199. return this._emptyCubeTexture;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Engine.prototype._rebuildInternalTextures = function () {
  12205. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12206. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12207. var internalTexture = currentState_1[_i];
  12208. internalTexture._rebuild();
  12209. }
  12210. };
  12211. Engine.prototype._rebuildEffects = function () {
  12212. for (var key in this._compiledEffects) {
  12213. var effect = this._compiledEffects[key];
  12214. effect._prepareEffect();
  12215. }
  12216. BABYLON.Effect.ResetCache();
  12217. };
  12218. Engine.prototype._rebuildBuffers = function () {
  12219. // Index / Vertex
  12220. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12221. var scene = _a[_i];
  12222. scene.resetCachedMaterial();
  12223. scene._rebuildGeometries();
  12224. scene._rebuildTextures();
  12225. }
  12226. // Uniforms
  12227. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12228. var uniformBuffer = _c[_b];
  12229. uniformBuffer._rebuild();
  12230. }
  12231. };
  12232. Engine.prototype._initGLContext = function () {
  12233. // Caps
  12234. this._caps = new EngineCapabilities();
  12235. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12236. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12237. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12238. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12239. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12240. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12241. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12242. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12243. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12244. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12245. // Infos
  12246. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12247. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12248. if (rendererInfo != null) {
  12249. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12250. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12251. }
  12252. if (!this._glVendor) {
  12253. this._glVendor = "Unknown vendor";
  12254. }
  12255. if (!this._glRenderer) {
  12256. this._glRenderer = "Unknown renderer";
  12257. }
  12258. // Constants
  12259. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12260. if (this._gl.RGBA16F !== 0x881A) {
  12261. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12262. }
  12263. if (this._gl.RGBA32F !== 0x8814) {
  12264. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12265. }
  12266. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12267. this._gl.DEPTH24_STENCIL8 = 35056;
  12268. }
  12269. // Extensions
  12270. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12271. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12272. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12273. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12274. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12275. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12276. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12277. 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');
  12278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12279. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12280. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12281. this._caps.highPrecisionShaderSupported = true;
  12282. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12283. if (this._caps.timerQuery) {
  12284. if (this._webGLVersion === 1) {
  12285. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12286. }
  12287. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12288. }
  12289. // Checks if some of the format renders first to allow the use of webgl inspector.
  12290. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12291. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12292. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12293. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12294. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12295. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12296. if (this._webGLVersion > 1) {
  12297. this._gl.HALF_FLOAT_OES = 0x140B;
  12298. }
  12299. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12300. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12301. // Draw buffers
  12302. if (this._webGLVersion > 1) {
  12303. this._caps.drawBuffersExtension = true;
  12304. }
  12305. else {
  12306. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12307. if (drawBuffersExtension !== null) {
  12308. this._caps.drawBuffersExtension = true;
  12309. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12310. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12311. for (var i = 0; i < 16; i++) {
  12312. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12313. }
  12314. }
  12315. else {
  12316. this._caps.drawBuffersExtension = false;
  12317. }
  12318. }
  12319. // Depth Texture
  12320. if (this._webGLVersion > 1) {
  12321. this._caps.depthTextureExtension = true;
  12322. }
  12323. else {
  12324. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12325. if (depthTextureExtension != null) {
  12326. this._caps.depthTextureExtension = true;
  12327. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12328. }
  12329. }
  12330. // Vertex array object
  12331. if (this._webGLVersion > 1) {
  12332. this._caps.vertexArrayObject = true;
  12333. }
  12334. else {
  12335. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12336. if (vertexArrayObjectExtension != null) {
  12337. this._caps.vertexArrayObject = true;
  12338. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12339. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12340. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12341. }
  12342. else {
  12343. this._caps.vertexArrayObject = false;
  12344. }
  12345. }
  12346. // Instances count
  12347. if (this._webGLVersion > 1) {
  12348. this._caps.instancedArrays = true;
  12349. }
  12350. else {
  12351. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12352. if (instanceExtension != null) {
  12353. this._caps.instancedArrays = true;
  12354. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12355. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12356. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12357. }
  12358. else {
  12359. this._caps.instancedArrays = false;
  12360. }
  12361. }
  12362. // Intelligently add supported compressed formats in order to check for.
  12363. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12364. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12365. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12366. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12367. if (this._caps.astc)
  12368. this.texturesSupported.push('-astc.ktx');
  12369. if (this._caps.s3tc)
  12370. this.texturesSupported.push('-dxt.ktx');
  12371. if (this._caps.pvrtc)
  12372. this.texturesSupported.push('-pvrtc.ktx');
  12373. if (this._caps.etc2)
  12374. this.texturesSupported.push('-etc2.ktx');
  12375. if (this._caps.etc1)
  12376. this.texturesSupported.push('-etc1.ktx');
  12377. if (this._gl.getShaderPrecisionFormat) {
  12378. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12379. if (highp) {
  12380. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12381. }
  12382. }
  12383. // Depth buffer
  12384. this.setDepthBuffer(true);
  12385. this.setDepthFunctionToLessOrEqual();
  12386. this.setDepthWrite(true);
  12387. // Texture maps
  12388. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12389. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12390. this._nextFreeTextureSlots.push(slot);
  12391. }
  12392. };
  12393. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12394. /**
  12395. * Gets version of the current webGL context
  12396. */
  12397. get: function () {
  12398. return this._webGLVersion;
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12404. /**
  12405. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12406. */
  12407. get: function () {
  12408. return this._isStencilEnable;
  12409. },
  12410. enumerable: true,
  12411. configurable: true
  12412. });
  12413. Engine.prototype._prepareWorkingCanvas = function () {
  12414. if (this._workingCanvas) {
  12415. return;
  12416. }
  12417. this._workingCanvas = document.createElement("canvas");
  12418. var context = this._workingCanvas.getContext("2d");
  12419. if (context) {
  12420. this._workingContext = context;
  12421. }
  12422. };
  12423. /**
  12424. * Reset the texture cache to empty state
  12425. */
  12426. Engine.prototype.resetTextureCache = function () {
  12427. for (var key in this._boundTexturesCache) {
  12428. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12429. continue;
  12430. }
  12431. var boundTexture = this._boundTexturesCache[key];
  12432. if (boundTexture) {
  12433. this._removeDesignatedSlot(boundTexture);
  12434. }
  12435. this._boundTexturesCache[key] = null;
  12436. }
  12437. if (!this.disableTextureBindingOptimization) {
  12438. this._nextFreeTextureSlots = [];
  12439. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12440. this._nextFreeTextureSlots.push(slot);
  12441. }
  12442. }
  12443. this._currentTextureChannel = -1;
  12444. };
  12445. /**
  12446. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12447. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12448. * @returns true if engine is in deterministic lock step mode
  12449. */
  12450. Engine.prototype.isDeterministicLockStep = function () {
  12451. return this._deterministicLockstep;
  12452. };
  12453. /**
  12454. * Gets the max steps when engine is running in deterministic lock step
  12455. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12456. * @returns the max steps
  12457. */
  12458. Engine.prototype.getLockstepMaxSteps = function () {
  12459. return this._lockstepMaxSteps;
  12460. };
  12461. /**
  12462. * Gets an object containing information about the current webGL context
  12463. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12464. */
  12465. Engine.prototype.getGlInfo = function () {
  12466. return {
  12467. vendor: this._glVendor,
  12468. renderer: this._glRenderer,
  12469. version: this._glVersion
  12470. };
  12471. };
  12472. /**
  12473. * Gets current aspect ratio
  12474. * @param camera defines the camera to use to get the aspect ratio
  12475. * @param useScreen defines if screen size must be used (or the current render target if any)
  12476. * @returns a number defining the aspect ratio
  12477. */
  12478. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12479. if (useScreen === void 0) { useScreen = false; }
  12480. var viewport = camera.viewport;
  12481. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12482. };
  12483. /**
  12484. * Gets current screen aspect ratio
  12485. * @returns a number defining the aspect ratio
  12486. */
  12487. Engine.prototype.getScreenAspectRatio = function () {
  12488. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12489. };
  12490. /**
  12491. * Gets the current render width
  12492. * @param useScreen defines if screen size must be used (or the current render target if any)
  12493. * @returns a number defining the current render width
  12494. */
  12495. Engine.prototype.getRenderWidth = function (useScreen) {
  12496. if (useScreen === void 0) { useScreen = false; }
  12497. if (!useScreen && this._currentRenderTarget) {
  12498. return this._currentRenderTarget.width;
  12499. }
  12500. return this._gl.drawingBufferWidth;
  12501. };
  12502. /**
  12503. * Gets the current render height
  12504. * @param useScreen defines if screen size must be used (or the current render target if any)
  12505. * @returns a number defining the current render height
  12506. */
  12507. Engine.prototype.getRenderHeight = function (useScreen) {
  12508. if (useScreen === void 0) { useScreen = false; }
  12509. if (!useScreen && this._currentRenderTarget) {
  12510. return this._currentRenderTarget.height;
  12511. }
  12512. return this._gl.drawingBufferHeight;
  12513. };
  12514. /**
  12515. * Gets the HTML canvas attached with the current webGL context
  12516. * @returns a HTML canvas
  12517. */
  12518. Engine.prototype.getRenderingCanvas = function () {
  12519. return this._renderingCanvas;
  12520. };
  12521. /**
  12522. * Gets the client rect of the HTML canvas attached with the current webGL context
  12523. * @returns a client rectanglee
  12524. */
  12525. Engine.prototype.getRenderingCanvasClientRect = function () {
  12526. if (!this._renderingCanvas) {
  12527. return null;
  12528. }
  12529. return this._renderingCanvas.getBoundingClientRect();
  12530. };
  12531. /**
  12532. * Defines the hardware scaling level.
  12533. * By default the hardware scaling level is computed from the window device ratio.
  12534. * 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.
  12535. * @param level defines the level to use
  12536. */
  12537. Engine.prototype.setHardwareScalingLevel = function (level) {
  12538. this._hardwareScalingLevel = level;
  12539. this.resize();
  12540. };
  12541. /**
  12542. * Gets the current hardware scaling level.
  12543. * By default the hardware scaling level is computed from the window device ratio.
  12544. * 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.
  12545. * @returns a number indicating the current hardware scaling level
  12546. */
  12547. Engine.prototype.getHardwareScalingLevel = function () {
  12548. return this._hardwareScalingLevel;
  12549. };
  12550. /**
  12551. * Gets the list of loaded textures
  12552. * @returns an array containing all loaded textures
  12553. */
  12554. Engine.prototype.getLoadedTexturesCache = function () {
  12555. return this._internalTexturesCache;
  12556. };
  12557. /**
  12558. * Gets the object containing all engine capabilities
  12559. * @returns the EngineCapabilities object
  12560. */
  12561. Engine.prototype.getCaps = function () {
  12562. return this._caps;
  12563. };
  12564. Object.defineProperty(Engine.prototype, "drawCalls", {
  12565. /** @hidden */
  12566. get: function () {
  12567. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12568. return 0;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12574. /** @hidden */
  12575. get: function () {
  12576. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12577. return null;
  12578. },
  12579. enumerable: true,
  12580. configurable: true
  12581. });
  12582. /**
  12583. * Gets the current depth function
  12584. * @returns a number defining the depth function
  12585. */
  12586. Engine.prototype.getDepthFunction = function () {
  12587. return this._depthCullingState.depthFunc;
  12588. };
  12589. /**
  12590. * Sets the current depth function
  12591. * @param depthFunc defines the function to use
  12592. */
  12593. Engine.prototype.setDepthFunction = function (depthFunc) {
  12594. this._depthCullingState.depthFunc = depthFunc;
  12595. };
  12596. /**
  12597. * Sets the current depth function to GREATER
  12598. */
  12599. Engine.prototype.setDepthFunctionToGreater = function () {
  12600. this._depthCullingState.depthFunc = this._gl.GREATER;
  12601. };
  12602. /**
  12603. * Sets the current depth function to GEQUAL
  12604. */
  12605. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12606. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12607. };
  12608. /**
  12609. * Sets the current depth function to LESS
  12610. */
  12611. Engine.prototype.setDepthFunctionToLess = function () {
  12612. this._depthCullingState.depthFunc = this._gl.LESS;
  12613. };
  12614. /**
  12615. * Sets the current depth function to LEQUAL
  12616. */
  12617. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12618. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12619. };
  12620. /**
  12621. * Gets a boolean indicating if stencil buffer is enabled
  12622. * @returns the current stencil buffer state
  12623. */
  12624. Engine.prototype.getStencilBuffer = function () {
  12625. return this._stencilState.stencilTest;
  12626. };
  12627. /**
  12628. * Enable or disable the stencil buffer
  12629. * @param enable defines if the stencil buffer must be enabled or disabled
  12630. */
  12631. Engine.prototype.setStencilBuffer = function (enable) {
  12632. this._stencilState.stencilTest = enable;
  12633. };
  12634. /**
  12635. * Gets the current stencil mask
  12636. * @returns a number defining the new stencil mask to use
  12637. */
  12638. Engine.prototype.getStencilMask = function () {
  12639. return this._stencilState.stencilMask;
  12640. };
  12641. /**
  12642. * Sets the current stencil mask
  12643. * @param mask defines the new stencil mask to use
  12644. */
  12645. Engine.prototype.setStencilMask = function (mask) {
  12646. this._stencilState.stencilMask = mask;
  12647. };
  12648. /**
  12649. * Gets the current stencil function
  12650. * @returns a number defining the stencil function to use
  12651. */
  12652. Engine.prototype.getStencilFunction = function () {
  12653. return this._stencilState.stencilFunc;
  12654. };
  12655. /**
  12656. * Gets the current stencil reference value
  12657. * @returns a number defining the stencil reference value to use
  12658. */
  12659. Engine.prototype.getStencilFunctionReference = function () {
  12660. return this._stencilState.stencilFuncRef;
  12661. };
  12662. /**
  12663. * Gets the current stencil mask
  12664. * @returns a number defining the stencil mask to use
  12665. */
  12666. Engine.prototype.getStencilFunctionMask = function () {
  12667. return this._stencilState.stencilFuncMask;
  12668. };
  12669. /**
  12670. * Sets the current stencil function
  12671. * @param stencilFunc defines the new stencil function to use
  12672. */
  12673. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12674. this._stencilState.stencilFunc = stencilFunc;
  12675. };
  12676. /**
  12677. * Sets the current stencil reference
  12678. * @param reference defines the new stencil reference to use
  12679. */
  12680. Engine.prototype.setStencilFunctionReference = function (reference) {
  12681. this._stencilState.stencilFuncRef = reference;
  12682. };
  12683. /**
  12684. * Sets the current stencil mask
  12685. * @param mask defines the new stencil mask to use
  12686. */
  12687. Engine.prototype.setStencilFunctionMask = function (mask) {
  12688. this._stencilState.stencilFuncMask = mask;
  12689. };
  12690. /**
  12691. * Gets the current stencil operation when stencil fails
  12692. * @returns a number defining stencil operation to use when stencil fails
  12693. */
  12694. Engine.prototype.getStencilOperationFail = function () {
  12695. return this._stencilState.stencilOpStencilFail;
  12696. };
  12697. /**
  12698. * Gets the current stencil operation when depth fails
  12699. * @returns a number defining stencil operation to use when depth fails
  12700. */
  12701. Engine.prototype.getStencilOperationDepthFail = function () {
  12702. return this._stencilState.stencilOpDepthFail;
  12703. };
  12704. /**
  12705. * Gets the current stencil operation when stencil passes
  12706. * @returns a number defining stencil operation to use when stencil passes
  12707. */
  12708. Engine.prototype.getStencilOperationPass = function () {
  12709. return this._stencilState.stencilOpStencilDepthPass;
  12710. };
  12711. /**
  12712. * Sets the stencil operation to use when stencil fails
  12713. * @param operation defines the stencil operation to use when stencil fails
  12714. */
  12715. Engine.prototype.setStencilOperationFail = function (operation) {
  12716. this._stencilState.stencilOpStencilFail = operation;
  12717. };
  12718. /**
  12719. * Sets the stencil operation to use when depth fails
  12720. * @param operation defines the stencil operation to use when depth fails
  12721. */
  12722. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12723. this._stencilState.stencilOpDepthFail = operation;
  12724. };
  12725. /**
  12726. * Sets the stencil operation to use when stencil passes
  12727. * @param operation defines the stencil operation to use when stencil passes
  12728. */
  12729. Engine.prototype.setStencilOperationPass = function (operation) {
  12730. this._stencilState.stencilOpStencilDepthPass = operation;
  12731. };
  12732. /**
  12733. * Sets a boolean indicating if the dithering state is enabled or disabled
  12734. * @param value defines the dithering state
  12735. */
  12736. Engine.prototype.setDitheringState = function (value) {
  12737. if (value) {
  12738. this._gl.enable(this._gl.DITHER);
  12739. }
  12740. else {
  12741. this._gl.disable(this._gl.DITHER);
  12742. }
  12743. };
  12744. /**
  12745. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12746. * @param value defines the rasterizer state
  12747. */
  12748. Engine.prototype.setRasterizerState = function (value) {
  12749. if (value) {
  12750. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12751. }
  12752. else {
  12753. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12754. }
  12755. };
  12756. /**
  12757. * stop executing a render loop function and remove it from the execution array
  12758. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12759. */
  12760. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12761. if (!renderFunction) {
  12762. this._activeRenderLoops = [];
  12763. return;
  12764. }
  12765. var index = this._activeRenderLoops.indexOf(renderFunction);
  12766. if (index >= 0) {
  12767. this._activeRenderLoops.splice(index, 1);
  12768. }
  12769. };
  12770. /** @hidden */
  12771. Engine.prototype._renderLoop = function () {
  12772. if (!this._contextWasLost) {
  12773. var shouldRender = true;
  12774. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12775. shouldRender = false;
  12776. }
  12777. if (shouldRender) {
  12778. // Start new frame
  12779. this.beginFrame();
  12780. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12781. var renderFunction = this._activeRenderLoops[index];
  12782. renderFunction();
  12783. }
  12784. // Present
  12785. this.endFrame();
  12786. }
  12787. }
  12788. if (this._activeRenderLoops.length > 0) {
  12789. // Register new frame
  12790. var requester = null;
  12791. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12792. requester = this._vrDisplay;
  12793. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12794. }
  12795. else {
  12796. this._renderingQueueLaunched = false;
  12797. }
  12798. };
  12799. /**
  12800. * Register and execute a render loop. The engine can have more than one render function
  12801. * @param renderFunction defines the function to continuously execute
  12802. */
  12803. Engine.prototype.runRenderLoop = function (renderFunction) {
  12804. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12805. return;
  12806. }
  12807. this._activeRenderLoops.push(renderFunction);
  12808. if (!this._renderingQueueLaunched) {
  12809. this._renderingQueueLaunched = true;
  12810. this._bindedRenderFunction = this._renderLoop.bind(this);
  12811. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12812. }
  12813. };
  12814. /**
  12815. * Toggle full screen mode
  12816. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12817. * @param options defines an option object to be sent to the requestFullscreen function
  12818. */
  12819. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12820. if (this.isFullscreen) {
  12821. BABYLON.Tools.ExitFullscreen();
  12822. }
  12823. else {
  12824. this._pointerLockRequested = requestPointerLock;
  12825. if (this._renderingCanvas) {
  12826. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12827. }
  12828. }
  12829. };
  12830. /**
  12831. * Clear the current render buffer or the current render target (if any is set up)
  12832. * @param color defines the color to use
  12833. * @param backBuffer defines if the back buffer must be cleared
  12834. * @param depth defines if the depth buffer must be cleared
  12835. * @param stencil defines if the stencil buffer must be cleared
  12836. */
  12837. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12838. if (stencil === void 0) { stencil = false; }
  12839. this.applyStates();
  12840. var mode = 0;
  12841. if (backBuffer && color) {
  12842. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12843. mode |= this._gl.COLOR_BUFFER_BIT;
  12844. }
  12845. if (depth) {
  12846. this._gl.clearDepth(1.0);
  12847. mode |= this._gl.DEPTH_BUFFER_BIT;
  12848. }
  12849. if (stencil) {
  12850. this._gl.clearStencil(0);
  12851. mode |= this._gl.STENCIL_BUFFER_BIT;
  12852. }
  12853. this._gl.clear(mode);
  12854. };
  12855. /**
  12856. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12857. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12858. * @param y defines the y-coordinate of the corner of the clear rectangle
  12859. * @param width defines the width of the clear rectangle
  12860. * @param height defines the height of the clear rectangle
  12861. * @param clearColor defines the clear color
  12862. */
  12863. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12864. var gl = this._gl;
  12865. // Save state
  12866. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12867. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12868. // Change state
  12869. gl.enable(gl.SCISSOR_TEST);
  12870. gl.scissor(x, y, width, height);
  12871. // Clear
  12872. this.clear(clearColor, true, true, true);
  12873. // Restore state
  12874. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12875. if (curScissor === true) {
  12876. gl.enable(gl.SCISSOR_TEST);
  12877. }
  12878. else {
  12879. gl.disable(gl.SCISSOR_TEST);
  12880. }
  12881. };
  12882. /** @hidden */
  12883. Engine.prototype._viewport = function (x, y, width, height) {
  12884. if (x !== this._viewportCached.x ||
  12885. y !== this._viewportCached.y ||
  12886. width !== this._viewportCached.z ||
  12887. height !== this._viewportCached.w) {
  12888. this._viewportCached.x = x;
  12889. this._viewportCached.y = y;
  12890. this._viewportCached.z = width;
  12891. this._viewportCached.w = height;
  12892. this._gl.viewport(x, y, width, height);
  12893. }
  12894. };
  12895. /**
  12896. * Set the WebGL's viewport
  12897. * @param viewport defines the viewport element to be used
  12898. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12899. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12900. */
  12901. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12902. var width = requiredWidth || this.getRenderWidth();
  12903. var height = requiredHeight || this.getRenderHeight();
  12904. var x = viewport.x || 0;
  12905. var y = viewport.y || 0;
  12906. this._cachedViewport = viewport;
  12907. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12908. };
  12909. /**
  12910. * Directly set the WebGL Viewport
  12911. * @param x defines the x coordinate of the viewport (in screen space)
  12912. * @param y defines the y coordinate of the viewport (in screen space)
  12913. * @param width defines the width of the viewport (in screen space)
  12914. * @param height defines the height of the viewport (in screen space)
  12915. * @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
  12916. */
  12917. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12918. var currentViewport = this._cachedViewport;
  12919. this._cachedViewport = null;
  12920. this._viewport(x, y, width, height);
  12921. return currentViewport;
  12922. };
  12923. /**
  12924. * Begin a new frame
  12925. */
  12926. Engine.prototype.beginFrame = function () {
  12927. this.onBeginFrameObservable.notifyObservers(this);
  12928. this._measureFps();
  12929. };
  12930. /**
  12931. * Enf the current frame
  12932. */
  12933. Engine.prototype.endFrame = function () {
  12934. // Force a flush in case we are using a bad OS.
  12935. if (this._badOS) {
  12936. this.flushFramebuffer();
  12937. }
  12938. // Submit frame to the vr device, if enabled
  12939. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12940. // TODO: We should only submit the frame if we read frameData successfully.
  12941. this._vrDisplay.submitFrame();
  12942. }
  12943. this.onEndFrameObservable.notifyObservers(this);
  12944. };
  12945. /**
  12946. * Resize the view according to the canvas' size
  12947. */
  12948. Engine.prototype.resize = function () {
  12949. // We're not resizing the size of the canvas while in VR mode & presenting
  12950. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12951. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12952. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12953. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12954. }
  12955. };
  12956. /**
  12957. * Force a specific size of the canvas
  12958. * @param width defines the new canvas' width
  12959. * @param height defines the new canvas' height
  12960. */
  12961. Engine.prototype.setSize = function (width, height) {
  12962. if (!this._renderingCanvas) {
  12963. return;
  12964. }
  12965. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12966. return;
  12967. }
  12968. this._renderingCanvas.width = width;
  12969. this._renderingCanvas.height = height;
  12970. for (var index = 0; index < this.scenes.length; index++) {
  12971. var scene = this.scenes[index];
  12972. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12973. var cam = scene.cameras[camIndex];
  12974. cam._currentRenderId = 0;
  12975. }
  12976. }
  12977. if (this.onResizeObservable.hasObservers) {
  12978. this.onResizeObservable.notifyObservers(this);
  12979. }
  12980. };
  12981. // WebVR functions
  12982. /**
  12983. * Gets a boolean indicating if a webVR device was detected
  12984. * @returns true if a webVR device was detected
  12985. */
  12986. Engine.prototype.isVRDevicePresent = function () {
  12987. return !!this._vrDisplay;
  12988. };
  12989. /**
  12990. * Gets the current webVR device
  12991. * @returns the current webVR device (or null)
  12992. */
  12993. Engine.prototype.getVRDevice = function () {
  12994. return this._vrDisplay;
  12995. };
  12996. /**
  12997. * Initializes a webVR display and starts listening to display change events
  12998. * The onVRDisplayChangedObservable will be notified upon these changes
  12999. * @returns The onVRDisplayChangedObservable
  13000. */
  13001. Engine.prototype.initWebVR = function () {
  13002. this.initWebVRAsync();
  13003. return this.onVRDisplayChangedObservable;
  13004. };
  13005. /**
  13006. * Initializes a webVR display and starts listening to display change events
  13007. * The onVRDisplayChangedObservable will be notified upon these changes
  13008. * @returns A promise containing a VRDisplay and if vr is supported
  13009. */
  13010. Engine.prototype.initWebVRAsync = function () {
  13011. var _this = this;
  13012. var notifyObservers = function () {
  13013. var eventArgs = {
  13014. vrDisplay: _this._vrDisplay,
  13015. vrSupported: _this._vrSupported
  13016. };
  13017. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13018. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13019. };
  13020. if (!this._onVrDisplayConnect) {
  13021. this._onVrDisplayConnect = function (event) {
  13022. _this._vrDisplay = event.display;
  13023. notifyObservers();
  13024. };
  13025. this._onVrDisplayDisconnect = function () {
  13026. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13027. _this._vrDisplay = undefined;
  13028. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13029. notifyObservers();
  13030. };
  13031. this._onVrDisplayPresentChange = function () {
  13032. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13033. };
  13034. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13035. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13036. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13037. }
  13038. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13039. this._webVRInitPromise.then(notifyObservers);
  13040. return this._webVRInitPromise;
  13041. };
  13042. /**
  13043. * Call this function to switch to webVR mode
  13044. * Will do nothing if webVR is not supported or if there is no webVR device
  13045. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13046. */
  13047. Engine.prototype.enableVR = function () {
  13048. var _this = this;
  13049. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13050. var onResolved = function () {
  13051. _this.onVRRequestPresentComplete.notifyObservers(true);
  13052. _this._onVRFullScreenTriggered();
  13053. };
  13054. var onRejected = function () {
  13055. _this.onVRRequestPresentComplete.notifyObservers(false);
  13056. };
  13057. this.onVRRequestPresentStart.notifyObservers(this);
  13058. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13059. }
  13060. };
  13061. /**
  13062. * Call this function to leave webVR mode
  13063. * Will do nothing if webVR is not supported or if there is no webVR device
  13064. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13065. */
  13066. Engine.prototype.disableVR = function () {
  13067. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13068. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13069. }
  13070. };
  13071. Engine.prototype._getVRDisplaysAsync = function () {
  13072. var _this = this;
  13073. return new Promise(function (res, rej) {
  13074. if (navigator.getVRDisplays) {
  13075. navigator.getVRDisplays().then(function (devices) {
  13076. _this._vrSupported = true;
  13077. // note that devices may actually be an empty array. This is fine;
  13078. // we expect this._vrDisplay to be undefined in this case.
  13079. _this._vrDisplay = devices[0];
  13080. res({
  13081. vrDisplay: _this._vrDisplay,
  13082. vrSupported: _this._vrSupported
  13083. });
  13084. });
  13085. }
  13086. else {
  13087. _this._vrDisplay = undefined;
  13088. _this._vrSupported = false;
  13089. res({
  13090. vrDisplay: _this._vrDisplay,
  13091. vrSupported: _this._vrSupported
  13092. });
  13093. }
  13094. });
  13095. };
  13096. /**
  13097. * Binds the frame buffer to the specified texture.
  13098. * @param texture The texture to render to or null for the default canvas
  13099. * @param faceIndex The face of the texture to render to in case of cube texture
  13100. * @param requiredWidth The width of the target to render to
  13101. * @param requiredHeight The height of the target to render to
  13102. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13103. * @param depthStencilTexture The depth stencil texture to use to render
  13104. * @param lodLevel defines le lod level to bind to the frame buffer
  13105. */
  13106. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13107. if (lodLevel === void 0) { lodLevel = 0; }
  13108. if (this._currentRenderTarget) {
  13109. this.unBindFramebuffer(this._currentRenderTarget);
  13110. }
  13111. this._currentRenderTarget = texture;
  13112. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13113. var gl = this._gl;
  13114. if (texture.isCube) {
  13115. if (faceIndex === undefined) {
  13116. faceIndex = 0;
  13117. }
  13118. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13119. if (depthStencilTexture) {
  13120. if (depthStencilTexture._generateStencilBuffer) {
  13121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13122. }
  13123. else {
  13124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13125. }
  13126. }
  13127. }
  13128. if (this._cachedViewport && !forceFullscreenViewport) {
  13129. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13130. }
  13131. else {
  13132. if (!requiredWidth) {
  13133. requiredWidth = texture.width;
  13134. if (lodLevel) {
  13135. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13136. }
  13137. }
  13138. if (!requiredHeight) {
  13139. requiredHeight = texture.height;
  13140. if (lodLevel) {
  13141. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13142. }
  13143. }
  13144. this._viewport(0, 0, requiredWidth, requiredHeight);
  13145. }
  13146. this.wipeCaches();
  13147. };
  13148. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13149. if (this._currentFramebuffer !== framebuffer) {
  13150. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13151. this._currentFramebuffer = framebuffer;
  13152. }
  13153. };
  13154. /**
  13155. * Unbind the current render target texture from the webGL context
  13156. * @param texture defines the render target texture to unbind
  13157. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13158. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13159. */
  13160. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13161. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13162. this._currentRenderTarget = null;
  13163. // If MSAA, we need to bitblt back to main texture
  13164. var gl = this._gl;
  13165. if (texture._MSAAFramebuffer) {
  13166. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13167. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13168. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13169. }
  13170. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13171. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13172. gl.generateMipmap(gl.TEXTURE_2D);
  13173. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13174. }
  13175. if (onBeforeUnbind) {
  13176. if (texture._MSAAFramebuffer) {
  13177. // Bind the correct framebuffer
  13178. this.bindUnboundFramebuffer(texture._framebuffer);
  13179. }
  13180. onBeforeUnbind();
  13181. }
  13182. this.bindUnboundFramebuffer(null);
  13183. };
  13184. /**
  13185. * Unbind a list of render target textures from the webGL context
  13186. * This is used only when drawBuffer extension or webGL2 are active
  13187. * @param textures defines the render target textures to unbind
  13188. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13189. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13190. */
  13191. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13192. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13193. this._currentRenderTarget = null;
  13194. // If MSAA, we need to bitblt back to main texture
  13195. var gl = this._gl;
  13196. if (textures[0]._MSAAFramebuffer) {
  13197. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13198. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13199. var attachments = textures[0]._attachments;
  13200. if (!attachments) {
  13201. attachments = new Array(textures.length);
  13202. textures[0]._attachments = attachments;
  13203. }
  13204. for (var i = 0; i < textures.length; i++) {
  13205. var texture = textures[i];
  13206. for (var j = 0; j < attachments.length; j++) {
  13207. attachments[j] = gl.NONE;
  13208. }
  13209. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13210. gl.readBuffer(attachments[i]);
  13211. gl.drawBuffers(attachments);
  13212. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13213. }
  13214. for (var i = 0; i < attachments.length; i++) {
  13215. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13216. }
  13217. gl.drawBuffers(attachments);
  13218. }
  13219. for (var i = 0; i < textures.length; i++) {
  13220. var texture = textures[i];
  13221. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13222. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13223. gl.generateMipmap(gl.TEXTURE_2D);
  13224. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13225. }
  13226. }
  13227. if (onBeforeUnbind) {
  13228. if (textures[0]._MSAAFramebuffer) {
  13229. // Bind the correct framebuffer
  13230. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13231. }
  13232. onBeforeUnbind();
  13233. }
  13234. this.bindUnboundFramebuffer(null);
  13235. };
  13236. /**
  13237. * Force the mipmap generation for the given render target texture
  13238. * @param texture defines the render target texture to use
  13239. */
  13240. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13241. if (texture.generateMipMaps) {
  13242. var gl = this._gl;
  13243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13244. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13245. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13246. }
  13247. };
  13248. /**
  13249. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13250. */
  13251. Engine.prototype.flushFramebuffer = function () {
  13252. this._gl.flush();
  13253. };
  13254. /**
  13255. * Unbind the current render target and bind the default framebuffer
  13256. */
  13257. Engine.prototype.restoreDefaultFramebuffer = function () {
  13258. if (this._currentRenderTarget) {
  13259. this.unBindFramebuffer(this._currentRenderTarget);
  13260. }
  13261. else {
  13262. this.bindUnboundFramebuffer(null);
  13263. }
  13264. if (this._cachedViewport) {
  13265. this.setViewport(this._cachedViewport);
  13266. }
  13267. this.wipeCaches();
  13268. };
  13269. // UBOs
  13270. /**
  13271. * Create an uniform buffer
  13272. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13273. * @param elements defines the content of the uniform buffer
  13274. * @returns the webGL uniform buffer
  13275. */
  13276. Engine.prototype.createUniformBuffer = function (elements) {
  13277. var ubo = this._gl.createBuffer();
  13278. if (!ubo) {
  13279. throw new Error("Unable to create uniform buffer");
  13280. }
  13281. this.bindUniformBuffer(ubo);
  13282. if (elements instanceof Float32Array) {
  13283. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13287. }
  13288. this.bindUniformBuffer(null);
  13289. ubo.references = 1;
  13290. return ubo;
  13291. };
  13292. /**
  13293. * Create a dynamic uniform buffer
  13294. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13295. * @param elements defines the content of the uniform buffer
  13296. * @returns the webGL uniform buffer
  13297. */
  13298. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13299. var ubo = this._gl.createBuffer();
  13300. if (!ubo) {
  13301. throw new Error("Unable to create dynamic uniform buffer");
  13302. }
  13303. this.bindUniformBuffer(ubo);
  13304. if (elements instanceof Float32Array) {
  13305. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13306. }
  13307. else {
  13308. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13309. }
  13310. this.bindUniformBuffer(null);
  13311. ubo.references = 1;
  13312. return ubo;
  13313. };
  13314. /**
  13315. * Update an existing uniform buffer
  13316. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13317. * @param uniformBuffer defines the target uniform buffer
  13318. * @param elements defines the content to update
  13319. * @param offset defines the offset in the uniform buffer where update should start
  13320. * @param count defines the size of the data to update
  13321. */
  13322. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13323. this.bindUniformBuffer(uniformBuffer);
  13324. if (offset === undefined) {
  13325. offset = 0;
  13326. }
  13327. if (count === undefined) {
  13328. if (elements instanceof Float32Array) {
  13329. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13330. }
  13331. else {
  13332. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13333. }
  13334. }
  13335. else {
  13336. if (elements instanceof Float32Array) {
  13337. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13338. }
  13339. else {
  13340. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13341. }
  13342. }
  13343. this.bindUniformBuffer(null);
  13344. };
  13345. // VBOs
  13346. Engine.prototype._resetVertexBufferBinding = function () {
  13347. this.bindArrayBuffer(null);
  13348. this._cachedVertexBuffers = null;
  13349. };
  13350. /**
  13351. * Creates a vertex buffer
  13352. * @param data the data for the vertex buffer
  13353. * @returns the new WebGL static buffer
  13354. */
  13355. Engine.prototype.createVertexBuffer = function (data) {
  13356. var vbo = this._gl.createBuffer();
  13357. if (!vbo) {
  13358. throw new Error("Unable to create vertex buffer");
  13359. }
  13360. this.bindArrayBuffer(vbo);
  13361. if (data instanceof Array) {
  13362. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13363. }
  13364. else {
  13365. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13366. }
  13367. this._resetVertexBufferBinding();
  13368. vbo.references = 1;
  13369. return vbo;
  13370. };
  13371. /**
  13372. * Creates a dynamic vertex buffer
  13373. * @param data the data for the dynamic vertex buffer
  13374. * @returns the new WebGL dynamic buffer
  13375. */
  13376. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13377. var vbo = this._gl.createBuffer();
  13378. if (!vbo) {
  13379. throw new Error("Unable to create dynamic vertex buffer");
  13380. }
  13381. this.bindArrayBuffer(vbo);
  13382. if (data instanceof Array) {
  13383. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13384. }
  13385. else {
  13386. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13387. }
  13388. this._resetVertexBufferBinding();
  13389. vbo.references = 1;
  13390. return vbo;
  13391. };
  13392. /**
  13393. * Update a dynamic index buffer
  13394. * @param indexBuffer defines the target index buffer
  13395. * @param indices defines the data to update
  13396. * @param offset defines the offset in the target index buffer where update should start
  13397. */
  13398. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13399. if (offset === void 0) { offset = 0; }
  13400. // Force cache update
  13401. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13402. this.bindIndexBuffer(indexBuffer);
  13403. var arrayBuffer;
  13404. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13405. arrayBuffer = indices;
  13406. }
  13407. else {
  13408. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13409. }
  13410. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13411. this._resetIndexBufferBinding();
  13412. };
  13413. /**
  13414. * Updates a dynamic vertex buffer.
  13415. * @param vertexBuffer the vertex buffer to update
  13416. * @param data the data used to update the vertex buffer
  13417. * @param byteOffset the byte offset of the data
  13418. * @param byteLength the byte length of the data
  13419. */
  13420. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13421. this.bindArrayBuffer(vertexBuffer);
  13422. if (byteOffset === undefined) {
  13423. byteOffset = 0;
  13424. }
  13425. if (byteLength === undefined) {
  13426. if (data instanceof Array) {
  13427. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13428. }
  13429. else {
  13430. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13431. }
  13432. }
  13433. else {
  13434. if (data instanceof Array) {
  13435. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13436. }
  13437. else {
  13438. if (data instanceof ArrayBuffer) {
  13439. data = new Uint8Array(data, byteOffset, byteLength);
  13440. }
  13441. else {
  13442. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13443. }
  13444. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13445. }
  13446. }
  13447. this._resetVertexBufferBinding();
  13448. };
  13449. Engine.prototype._resetIndexBufferBinding = function () {
  13450. this.bindIndexBuffer(null);
  13451. this._cachedIndexBuffer = null;
  13452. };
  13453. /**
  13454. * Creates a new index buffer
  13455. * @param indices defines the content of the index buffer
  13456. * @param updatable defines if the index buffer must be updatable
  13457. * @returns a new webGL buffer
  13458. */
  13459. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13460. var vbo = this._gl.createBuffer();
  13461. if (!vbo) {
  13462. throw new Error("Unable to create index buffer");
  13463. }
  13464. this.bindIndexBuffer(vbo);
  13465. // Check for 32 bits indices
  13466. var arrayBuffer;
  13467. var need32Bits = false;
  13468. if (indices instanceof Uint16Array) {
  13469. arrayBuffer = indices;
  13470. }
  13471. else {
  13472. //check 32 bit support
  13473. if (this._caps.uintIndices) {
  13474. if (indices instanceof Uint32Array) {
  13475. arrayBuffer = indices;
  13476. need32Bits = true;
  13477. }
  13478. else {
  13479. //number[] or Int32Array, check if 32 bit is necessary
  13480. for (var index = 0; index < indices.length; index++) {
  13481. if (indices[index] > 65535) {
  13482. need32Bits = true;
  13483. break;
  13484. }
  13485. }
  13486. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13487. }
  13488. }
  13489. else {
  13490. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13491. arrayBuffer = new Uint16Array(indices);
  13492. }
  13493. }
  13494. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13495. this._resetIndexBufferBinding();
  13496. vbo.references = 1;
  13497. vbo.is32Bits = need32Bits;
  13498. return vbo;
  13499. };
  13500. /**
  13501. * Bind a webGL buffer to the webGL context
  13502. * @param buffer defines the buffer to bind
  13503. */
  13504. Engine.prototype.bindArrayBuffer = function (buffer) {
  13505. if (!this._vaoRecordInProgress) {
  13506. this._unbindVertexArrayObject();
  13507. }
  13508. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13509. };
  13510. /**
  13511. * Bind an uniform buffer to the current webGL context
  13512. * @param buffer defines the buffer to bind
  13513. */
  13514. Engine.prototype.bindUniformBuffer = function (buffer) {
  13515. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13516. };
  13517. /**
  13518. * Bind a buffer to the current webGL context at a given location
  13519. * @param buffer defines the buffer to bind
  13520. * @param location defines the index where to bind the buffer
  13521. */
  13522. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13523. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13524. };
  13525. /**
  13526. * Bind a specific block at a given index in a specific shader program
  13527. * @param shaderProgram defines the shader program
  13528. * @param blockName defines the block name
  13529. * @param index defines the index where to bind the block
  13530. */
  13531. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13532. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13533. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13534. };
  13535. ;
  13536. Engine.prototype.bindIndexBuffer = function (buffer) {
  13537. if (!this._vaoRecordInProgress) {
  13538. this._unbindVertexArrayObject();
  13539. }
  13540. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13541. };
  13542. Engine.prototype.bindBuffer = function (buffer, target) {
  13543. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13544. this._gl.bindBuffer(target, buffer);
  13545. this._currentBoundBuffer[target] = buffer;
  13546. }
  13547. };
  13548. /**
  13549. * update the bound buffer with the given data
  13550. * @param data defines the data to update
  13551. */
  13552. Engine.prototype.updateArrayBuffer = function (data) {
  13553. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13554. };
  13555. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13556. var pointer = this._currentBufferPointers[indx];
  13557. var changed = false;
  13558. if (!pointer.active) {
  13559. changed = true;
  13560. pointer.active = true;
  13561. pointer.index = indx;
  13562. pointer.size = size;
  13563. pointer.type = type;
  13564. pointer.normalized = normalized;
  13565. pointer.stride = stride;
  13566. pointer.offset = offset;
  13567. pointer.buffer = buffer;
  13568. }
  13569. else {
  13570. if (pointer.buffer !== buffer) {
  13571. pointer.buffer = buffer;
  13572. changed = true;
  13573. }
  13574. if (pointer.size !== size) {
  13575. pointer.size = size;
  13576. changed = true;
  13577. }
  13578. if (pointer.type !== type) {
  13579. pointer.type = type;
  13580. changed = true;
  13581. }
  13582. if (pointer.normalized !== normalized) {
  13583. pointer.normalized = normalized;
  13584. changed = true;
  13585. }
  13586. if (pointer.stride !== stride) {
  13587. pointer.stride = stride;
  13588. changed = true;
  13589. }
  13590. if (pointer.offset !== offset) {
  13591. pointer.offset = offset;
  13592. changed = true;
  13593. }
  13594. }
  13595. if (changed || this._vaoRecordInProgress) {
  13596. this.bindArrayBuffer(buffer);
  13597. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13598. }
  13599. };
  13600. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13601. if (indexBuffer == null) {
  13602. return;
  13603. }
  13604. if (this._cachedIndexBuffer !== indexBuffer) {
  13605. this._cachedIndexBuffer = indexBuffer;
  13606. this.bindIndexBuffer(indexBuffer);
  13607. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13608. }
  13609. };
  13610. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13611. var attributes = effect.getAttributesNames();
  13612. if (!this._vaoRecordInProgress) {
  13613. this._unbindVertexArrayObject();
  13614. }
  13615. this.unbindAllAttributes();
  13616. for (var index = 0; index < attributes.length; index++) {
  13617. var order = effect.getAttributeLocation(index);
  13618. if (order >= 0) {
  13619. var vertexBuffer = vertexBuffers[attributes[index]];
  13620. if (!vertexBuffer) {
  13621. continue;
  13622. }
  13623. this._gl.enableVertexAttribArray(order);
  13624. if (!this._vaoRecordInProgress) {
  13625. this._vertexAttribArraysEnabled[order] = true;
  13626. }
  13627. var buffer = vertexBuffer.getBuffer();
  13628. if (buffer) {
  13629. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13630. if (vertexBuffer.getIsInstanced()) {
  13631. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13632. if (!this._vaoRecordInProgress) {
  13633. this._currentInstanceLocations.push(order);
  13634. this._currentInstanceBuffers.push(buffer);
  13635. }
  13636. }
  13637. }
  13638. }
  13639. }
  13640. };
  13641. /**
  13642. * Records a vertex array object
  13643. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13644. * @param vertexBuffers defines the list of vertex buffers to store
  13645. * @param indexBuffer defines the index buffer to store
  13646. * @param effect defines the effect to store
  13647. * @returns the new vertex array object
  13648. */
  13649. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13650. var vao = this._gl.createVertexArray();
  13651. this._vaoRecordInProgress = true;
  13652. this._gl.bindVertexArray(vao);
  13653. this._mustWipeVertexAttributes = true;
  13654. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13655. this.bindIndexBuffer(indexBuffer);
  13656. this._vaoRecordInProgress = false;
  13657. this._gl.bindVertexArray(null);
  13658. return vao;
  13659. };
  13660. /**
  13661. * Bind a specific vertex array object
  13662. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13663. * @param vertexArrayObject defines the vertex array object to bind
  13664. * @param indexBuffer defines the index buffer to bind
  13665. */
  13666. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13667. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13668. this._cachedVertexArrayObject = vertexArrayObject;
  13669. this._gl.bindVertexArray(vertexArrayObject);
  13670. this._cachedVertexBuffers = null;
  13671. this._cachedIndexBuffer = null;
  13672. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13673. this._mustWipeVertexAttributes = true;
  13674. }
  13675. };
  13676. /**
  13677. * Bind webGl buffers directly to the webGL context
  13678. * @param vertexBuffer defines the vertex buffer to bind
  13679. * @param indexBuffer defines the index buffer to bind
  13680. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13681. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13682. * @param effect defines the effect associated with the vertex buffer
  13683. */
  13684. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13685. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13686. this._cachedVertexBuffers = vertexBuffer;
  13687. this._cachedEffectForVertexBuffers = effect;
  13688. var attributesCount = effect.getAttributesCount();
  13689. this._unbindVertexArrayObject();
  13690. this.unbindAllAttributes();
  13691. var offset = 0;
  13692. for (var index = 0; index < attributesCount; index++) {
  13693. if (index < vertexDeclaration.length) {
  13694. var order = effect.getAttributeLocation(index);
  13695. if (order >= 0) {
  13696. this._gl.enableVertexAttribArray(order);
  13697. this._vertexAttribArraysEnabled[order] = true;
  13698. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13699. }
  13700. offset += vertexDeclaration[index] * 4;
  13701. }
  13702. }
  13703. }
  13704. this._bindIndexBufferWithCache(indexBuffer);
  13705. };
  13706. Engine.prototype._unbindVertexArrayObject = function () {
  13707. if (!this._cachedVertexArrayObject) {
  13708. return;
  13709. }
  13710. this._cachedVertexArrayObject = null;
  13711. this._gl.bindVertexArray(null);
  13712. };
  13713. /**
  13714. * Bind a list of vertex buffers to the webGL context
  13715. * @param vertexBuffers defines the list of vertex buffers to bind
  13716. * @param indexBuffer defines the index buffer to bind
  13717. * @param effect defines the effect associated with the vertex buffers
  13718. */
  13719. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13720. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13721. this._cachedVertexBuffers = vertexBuffers;
  13722. this._cachedEffectForVertexBuffers = effect;
  13723. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13724. }
  13725. this._bindIndexBufferWithCache(indexBuffer);
  13726. };
  13727. /**
  13728. * Unbind all instance attributes
  13729. */
  13730. Engine.prototype.unbindInstanceAttributes = function () {
  13731. var boundBuffer;
  13732. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13733. var instancesBuffer = this._currentInstanceBuffers[i];
  13734. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13735. boundBuffer = instancesBuffer;
  13736. this.bindArrayBuffer(instancesBuffer);
  13737. }
  13738. var offsetLocation = this._currentInstanceLocations[i];
  13739. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13740. }
  13741. this._currentInstanceBuffers.length = 0;
  13742. this._currentInstanceLocations.length = 0;
  13743. };
  13744. /**
  13745. * Release and free the memory of a vertex array object
  13746. * @param vao defines the vertex array object to delete
  13747. */
  13748. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13749. this._gl.deleteVertexArray(vao);
  13750. };
  13751. /** @hidden */
  13752. Engine.prototype._releaseBuffer = function (buffer) {
  13753. buffer.references--;
  13754. if (buffer.references === 0) {
  13755. this._gl.deleteBuffer(buffer);
  13756. return true;
  13757. }
  13758. return false;
  13759. };
  13760. /**
  13761. * Creates a webGL buffer to use with instanciation
  13762. * @param capacity defines the size of the buffer
  13763. * @returns the webGL buffer
  13764. */
  13765. Engine.prototype.createInstancesBuffer = function (capacity) {
  13766. var buffer = this._gl.createBuffer();
  13767. if (!buffer) {
  13768. throw new Error("Unable to create instance buffer");
  13769. }
  13770. buffer.capacity = capacity;
  13771. this.bindArrayBuffer(buffer);
  13772. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13773. return buffer;
  13774. };
  13775. /**
  13776. * Delete a webGL buffer used with instanciation
  13777. * @param buffer defines the webGL buffer to delete
  13778. */
  13779. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13780. this._gl.deleteBuffer(buffer);
  13781. };
  13782. /**
  13783. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13784. * @param instancesBuffer defines the webGL buffer to update and bind
  13785. * @param data defines the data to store in the buffer
  13786. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13787. */
  13788. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13789. this.bindArrayBuffer(instancesBuffer);
  13790. if (data) {
  13791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13792. }
  13793. if (offsetLocations[0].index !== undefined) {
  13794. var stride = 0;
  13795. for (var i = 0; i < offsetLocations.length; i++) {
  13796. var ai = offsetLocations[i];
  13797. stride += ai.attributeSize * 4;
  13798. }
  13799. for (var i = 0; i < offsetLocations.length; i++) {
  13800. var ai = offsetLocations[i];
  13801. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13802. this._gl.enableVertexAttribArray(ai.index);
  13803. this._vertexAttribArraysEnabled[ai.index] = true;
  13804. }
  13805. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13806. this._gl.vertexAttribDivisor(ai.index, 1);
  13807. this._currentInstanceLocations.push(ai.index);
  13808. this._currentInstanceBuffers.push(instancesBuffer);
  13809. }
  13810. }
  13811. else {
  13812. for (var index = 0; index < 4; index++) {
  13813. var offsetLocation = offsetLocations[index];
  13814. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13815. this._gl.enableVertexAttribArray(offsetLocation);
  13816. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13817. }
  13818. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13819. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13820. this._currentInstanceLocations.push(offsetLocation);
  13821. this._currentInstanceBuffers.push(instancesBuffer);
  13822. }
  13823. }
  13824. };
  13825. /**
  13826. * Apply all cached states (depth, culling, stencil and alpha)
  13827. */
  13828. Engine.prototype.applyStates = function () {
  13829. this._depthCullingState.apply(this._gl);
  13830. this._stencilState.apply(this._gl);
  13831. this._alphaState.apply(this._gl);
  13832. };
  13833. /**
  13834. * Send a draw order
  13835. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13836. * @param indexStart defines the starting index
  13837. * @param indexCount defines the number of index to draw
  13838. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13839. */
  13840. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13841. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13842. };
  13843. /**
  13844. * Draw a list of points
  13845. * @param verticesStart defines the index of first vertex to draw
  13846. * @param verticesCount defines the count of vertices to draw
  13847. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13848. */
  13849. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13850. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13851. };
  13852. /**
  13853. * Draw a list of unindexed primitives
  13854. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13855. * @param verticesStart defines the index of first vertex to draw
  13856. * @param verticesCount defines the count of vertices to draw
  13857. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13858. */
  13859. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13860. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13861. };
  13862. /**
  13863. * Draw a list of indexed primitives
  13864. * @param fillMode defines the primitive to use
  13865. * @param indexStart defines the starting index
  13866. * @param indexCount defines the number of index to draw
  13867. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13868. */
  13869. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13870. // Apply states
  13871. this.applyStates();
  13872. this._drawCalls.addCount(1, false);
  13873. // Render
  13874. var drawMode = this._drawMode(fillMode);
  13875. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13876. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13877. if (instancesCount) {
  13878. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13879. }
  13880. else {
  13881. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13882. }
  13883. };
  13884. /**
  13885. * Draw a list of unindexed primitives
  13886. * @param fillMode defines the primitive to use
  13887. * @param verticesStart defines the index of first vertex to draw
  13888. * @param verticesCount defines the count of vertices to draw
  13889. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13890. */
  13891. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13892. // Apply states
  13893. this.applyStates();
  13894. this._drawCalls.addCount(1, false);
  13895. var drawMode = this._drawMode(fillMode);
  13896. if (instancesCount) {
  13897. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13898. }
  13899. else {
  13900. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13901. }
  13902. };
  13903. Engine.prototype._drawMode = function (fillMode) {
  13904. switch (fillMode) {
  13905. // Triangle views
  13906. case BABYLON.Material.TriangleFillMode:
  13907. return this._gl.TRIANGLES;
  13908. case BABYLON.Material.PointFillMode:
  13909. return this._gl.POINTS;
  13910. case BABYLON.Material.WireFrameFillMode:
  13911. return this._gl.LINES;
  13912. // Draw modes
  13913. case BABYLON.Material.PointListDrawMode:
  13914. return this._gl.POINTS;
  13915. case BABYLON.Material.LineListDrawMode:
  13916. return this._gl.LINES;
  13917. case BABYLON.Material.LineLoopDrawMode:
  13918. return this._gl.LINE_LOOP;
  13919. case BABYLON.Material.LineStripDrawMode:
  13920. return this._gl.LINE_STRIP;
  13921. case BABYLON.Material.TriangleStripDrawMode:
  13922. return this._gl.TRIANGLE_STRIP;
  13923. case BABYLON.Material.TriangleFanDrawMode:
  13924. return this._gl.TRIANGLE_FAN;
  13925. default:
  13926. return this._gl.TRIANGLES;
  13927. }
  13928. };
  13929. // Shaders
  13930. /** @hidden */
  13931. Engine.prototype._releaseEffect = function (effect) {
  13932. if (this._compiledEffects[effect._key]) {
  13933. delete this._compiledEffects[effect._key];
  13934. this._deleteProgram(effect.getProgram());
  13935. }
  13936. };
  13937. /** @hidden */
  13938. Engine.prototype._deleteProgram = function (program) {
  13939. if (program) {
  13940. program.__SPECTOR_rebuildProgram = null;
  13941. if (program.transformFeedback) {
  13942. this.deleteTransformFeedback(program.transformFeedback);
  13943. program.transformFeedback = null;
  13944. }
  13945. this._gl.deleteProgram(program);
  13946. }
  13947. };
  13948. /**
  13949. * Create a new effect (used to store vertex/fragment shaders)
  13950. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13951. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13952. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13953. * @param samplers defines an array of string used to represent textures
  13954. * @param defines defines the string containing the defines to use to compile the shaders
  13955. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13956. * @param onCompiled defines a function to call when the effect creation is successful
  13957. * @param onError defines a function to call when the effect creation has failed
  13958. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13959. * @returns the new Effect
  13960. */
  13961. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13962. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13963. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13964. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13965. if (this._compiledEffects[name]) {
  13966. var compiledEffect = this._compiledEffects[name];
  13967. if (onCompiled && compiledEffect.isReady()) {
  13968. onCompiled(compiledEffect);
  13969. }
  13970. return compiledEffect;
  13971. }
  13972. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13973. effect._key = name;
  13974. this._compiledEffects[name] = effect;
  13975. return effect;
  13976. };
  13977. /**
  13978. * Create an effect to use with particle systems.
  13979. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  13980. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13981. * @param uniformsNames defines a list of attribute names
  13982. * @param samplers defines an array of string used to represent textures
  13983. * @param defines defines the string containing the defines to use to compile the shaders
  13984. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13985. * @param onCompiled defines a function to call when the effect creation is successful
  13986. * @param onError defines a function to call when the effect creation has failed
  13987. * @returns the new Effect
  13988. */
  13989. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13990. if (uniformsNames === void 0) { uniformsNames = []; }
  13991. if (samplers === void 0) { samplers = []; }
  13992. if (defines === void 0) { defines = ""; }
  13993. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  13994. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  13995. defines += "\n#define BILLBOARD\n";
  13996. return this.createEffect({
  13997. vertex: "particles",
  13998. fragmentElement: fragmentName
  13999. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14000. };
  14001. /**
  14002. * Directly creates a webGL program
  14003. * @param vertexCode defines the vertex shader code to use
  14004. * @param fragmentCode defines the fragment shader code to use
  14005. * @param context defines the webGL context to use (if not set, the current one will be used)
  14006. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14007. * @returns the new webGL program
  14008. */
  14009. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14010. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14011. context = context || this._gl;
  14012. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14013. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14014. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14015. };
  14016. /**
  14017. * Creates a webGL program
  14018. * @param vertexCode defines the vertex shader code to use
  14019. * @param fragmentCode defines the fragment shader code to use
  14020. * @param defines defines the string containing the defines to use to compile the shaders
  14021. * @param context defines the webGL context to use (if not set, the current one will be used)
  14022. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14023. * @returns the new webGL program
  14024. */
  14025. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14026. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14027. context = context || this._gl;
  14028. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14029. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14030. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14031. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14032. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14033. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14034. return program;
  14035. };
  14036. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14037. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14038. var shaderProgram = context.createProgram();
  14039. if (!shaderProgram) {
  14040. throw new Error("Unable to create program");
  14041. }
  14042. context.attachShader(shaderProgram, vertexShader);
  14043. context.attachShader(shaderProgram, fragmentShader);
  14044. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14045. var transformFeedback = this.createTransformFeedback();
  14046. this.bindTransformFeedback(transformFeedback);
  14047. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14048. shaderProgram.transformFeedback = transformFeedback;
  14049. }
  14050. context.linkProgram(shaderProgram);
  14051. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14052. this.bindTransformFeedback(null);
  14053. }
  14054. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14055. if (!linked) {
  14056. context.validateProgram(shaderProgram);
  14057. var error = context.getProgramInfoLog(shaderProgram);
  14058. if (error) {
  14059. throw new Error(error);
  14060. }
  14061. }
  14062. context.deleteShader(vertexShader);
  14063. context.deleteShader(fragmentShader);
  14064. return shaderProgram;
  14065. };
  14066. /**
  14067. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14068. * @param shaderProgram defines the webGL program to use
  14069. * @param uniformsNames defines the list of uniform names
  14070. * @returns an array of webGL uniform locations
  14071. */
  14072. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14073. var results = new Array();
  14074. for (var index = 0; index < uniformsNames.length; index++) {
  14075. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14076. }
  14077. return results;
  14078. };
  14079. /**
  14080. * Gets the lsit of active attributes for a given webGL program
  14081. * @param shaderProgram defines the webGL program to use
  14082. * @param attributesNames defines the list of attribute names to get
  14083. * @returns an array of indices indicating the offset of each attribute
  14084. */
  14085. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14086. var results = [];
  14087. for (var index = 0; index < attributesNames.length; index++) {
  14088. try {
  14089. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14090. }
  14091. catch (e) {
  14092. results.push(-1);
  14093. }
  14094. }
  14095. return results;
  14096. };
  14097. /**
  14098. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14099. * @param effect defines the effect to activate
  14100. */
  14101. Engine.prototype.enableEffect = function (effect) {
  14102. if (!effect) {
  14103. return;
  14104. }
  14105. // Use program
  14106. this.bindSamplers(effect);
  14107. this._currentEffect = effect;
  14108. if (effect.onBind) {
  14109. effect.onBind(effect);
  14110. }
  14111. effect.onBindObservable.notifyObservers(effect);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to an array of int32
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param array defines the array of int32 to store
  14117. */
  14118. Engine.prototype.setIntArray = function (uniform, array) {
  14119. if (!uniform)
  14120. return;
  14121. this._gl.uniform1iv(uniform, array);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to an array of int32 (stored as vec2)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param array defines the array of int32 to store
  14127. */
  14128. Engine.prototype.setIntArray2 = function (uniform, array) {
  14129. if (!uniform || array.length % 2 !== 0)
  14130. return;
  14131. this._gl.uniform2iv(uniform, array);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to an array of int32 (stored as vec3)
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param array defines the array of int32 to store
  14137. */
  14138. Engine.prototype.setIntArray3 = function (uniform, array) {
  14139. if (!uniform || array.length % 3 !== 0)
  14140. return;
  14141. this._gl.uniform3iv(uniform, array);
  14142. };
  14143. /**
  14144. * Set the value of an uniform to an array of int32 (stored as vec4)
  14145. * @param uniform defines the webGL uniform location where to store the value
  14146. * @param array defines the array of int32 to store
  14147. */
  14148. Engine.prototype.setIntArray4 = function (uniform, array) {
  14149. if (!uniform || array.length % 4 !== 0)
  14150. return;
  14151. this._gl.uniform4iv(uniform, array);
  14152. };
  14153. /**
  14154. * Set the value of an uniform to an array of float32
  14155. * @param uniform defines the webGL uniform location where to store the value
  14156. * @param array defines the array of float32 to store
  14157. */
  14158. Engine.prototype.setFloatArray = function (uniform, array) {
  14159. if (!uniform)
  14160. return;
  14161. this._gl.uniform1fv(uniform, array);
  14162. };
  14163. /**
  14164. * Set the value of an uniform to an array of float32 (stored as vec2)
  14165. * @param uniform defines the webGL uniform location where to store the value
  14166. * @param array defines the array of float32 to store
  14167. */
  14168. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14169. if (!uniform || array.length % 2 !== 0)
  14170. return;
  14171. this._gl.uniform2fv(uniform, array);
  14172. };
  14173. /**
  14174. * Set the value of an uniform to an array of float32 (stored as vec3)
  14175. * @param uniform defines the webGL uniform location where to store the value
  14176. * @param array defines the array of float32 to store
  14177. */
  14178. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14179. if (!uniform || array.length % 3 !== 0)
  14180. return;
  14181. this._gl.uniform3fv(uniform, array);
  14182. };
  14183. /**
  14184. * Set the value of an uniform to an array of float32 (stored as vec4)
  14185. * @param uniform defines the webGL uniform location where to store the value
  14186. * @param array defines the array of float32 to store
  14187. */
  14188. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14189. if (!uniform || array.length % 4 !== 0)
  14190. return;
  14191. this._gl.uniform4fv(uniform, array);
  14192. };
  14193. /**
  14194. * Set the value of an uniform to an array of number
  14195. * @param uniform defines the webGL uniform location where to store the value
  14196. * @param array defines the array of number to store
  14197. */
  14198. Engine.prototype.setArray = function (uniform, array) {
  14199. if (!uniform)
  14200. return;
  14201. this._gl.uniform1fv(uniform, array);
  14202. };
  14203. /**
  14204. * Set the value of an uniform to an array of number (stored as vec2)
  14205. * @param uniform defines the webGL uniform location where to store the value
  14206. * @param array defines the array of number to store
  14207. */
  14208. Engine.prototype.setArray2 = function (uniform, array) {
  14209. if (!uniform || array.length % 2 !== 0)
  14210. return;
  14211. this._gl.uniform2fv(uniform, array);
  14212. };
  14213. /**
  14214. * Set the value of an uniform to an array of number (stored as vec3)
  14215. * @param uniform defines the webGL uniform location where to store the value
  14216. * @param array defines the array of number to store
  14217. */
  14218. Engine.prototype.setArray3 = function (uniform, array) {
  14219. if (!uniform || array.length % 3 !== 0)
  14220. return;
  14221. this._gl.uniform3fv(uniform, array);
  14222. };
  14223. /**
  14224. * Set the value of an uniform to an array of number (stored as vec4)
  14225. * @param uniform defines the webGL uniform location where to store the value
  14226. * @param array defines the array of number to store
  14227. */
  14228. Engine.prototype.setArray4 = function (uniform, array) {
  14229. if (!uniform || array.length % 4 !== 0)
  14230. return;
  14231. this._gl.uniform4fv(uniform, array);
  14232. };
  14233. /**
  14234. * Set the value of an uniform to an array of float32 (stored as matrices)
  14235. * @param uniform defines the webGL uniform location where to store the value
  14236. * @param matrices defines the array of float32 to store
  14237. */
  14238. Engine.prototype.setMatrices = function (uniform, matrices) {
  14239. if (!uniform)
  14240. return;
  14241. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14242. };
  14243. /**
  14244. * Set the value of an uniform to a matrix
  14245. * @param uniform defines the webGL uniform location where to store the value
  14246. * @param matrix defines the matrix to store
  14247. */
  14248. Engine.prototype.setMatrix = function (uniform, matrix) {
  14249. if (!uniform)
  14250. return;
  14251. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14252. };
  14253. /**
  14254. * Set the value of an uniform to a matrix (3x3)
  14255. * @param uniform defines the webGL uniform location where to store the value
  14256. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14257. */
  14258. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14259. if (!uniform)
  14260. return;
  14261. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14262. };
  14263. /**
  14264. * Set the value of an uniform to a matrix (2x2)
  14265. * @param uniform defines the webGL uniform location where to store the value
  14266. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14267. */
  14268. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14269. if (!uniform)
  14270. return;
  14271. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14272. };
  14273. /**
  14274. * Set the value of an uniform to a number (int)
  14275. * @param uniform defines the webGL uniform location where to store the value
  14276. * @param value defines the int number to store
  14277. */
  14278. Engine.prototype.setInt = function (uniform, value) {
  14279. if (!uniform)
  14280. return;
  14281. this._gl.uniform1i(uniform, value);
  14282. };
  14283. /**
  14284. * Set the value of an uniform to a number (float)
  14285. * @param uniform defines the webGL uniform location where to store the value
  14286. * @param value defines the float number to store
  14287. */
  14288. Engine.prototype.setFloat = function (uniform, value) {
  14289. if (!uniform)
  14290. return;
  14291. this._gl.uniform1f(uniform, value);
  14292. };
  14293. /**
  14294. * Set the value of an uniform to a vec2
  14295. * @param uniform defines the webGL uniform location where to store the value
  14296. * @param x defines the 1st component of the value
  14297. * @param y defines the 2nd component of the value
  14298. */
  14299. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14300. if (!uniform)
  14301. return;
  14302. this._gl.uniform2f(uniform, x, y);
  14303. };
  14304. /**
  14305. * Set the value of an uniform to a vec3
  14306. * @param uniform defines the webGL uniform location where to store the value
  14307. * @param x defines the 1st component of the value
  14308. * @param y defines the 2nd component of the value
  14309. * @param z defines the 3rd component of the value
  14310. */
  14311. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14312. if (!uniform)
  14313. return;
  14314. this._gl.uniform3f(uniform, x, y, z);
  14315. };
  14316. /**
  14317. * Set the value of an uniform to a boolean
  14318. * @param uniform defines the webGL uniform location where to store the value
  14319. * @param bool defines the boolean to store
  14320. */
  14321. Engine.prototype.setBool = function (uniform, bool) {
  14322. if (!uniform)
  14323. return;
  14324. this._gl.uniform1i(uniform, bool);
  14325. };
  14326. /**
  14327. * Set the value of an uniform to a vec4
  14328. * @param uniform defines the webGL uniform location where to store the value
  14329. * @param x defines the 1st component of the value
  14330. * @param y defines the 2nd component of the value
  14331. * @param z defines the 3rd component of the value
  14332. * @param w defines the 4th component of the value
  14333. */
  14334. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14335. if (!uniform)
  14336. return;
  14337. this._gl.uniform4f(uniform, x, y, z, w);
  14338. };
  14339. /**
  14340. * Set the value of an uniform to a Color3
  14341. * @param uniform defines the webGL uniform location where to store the value
  14342. * @param color3 defines the color to store
  14343. */
  14344. Engine.prototype.setColor3 = function (uniform, color3) {
  14345. if (!uniform)
  14346. return;
  14347. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14348. };
  14349. /**
  14350. * Set the value of an uniform to a Color3 and an alpha value
  14351. * @param uniform defines the webGL uniform location where to store the value
  14352. * @param color3 defines the color to store
  14353. * @param alpha defines the alpha component to store
  14354. */
  14355. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14356. if (!uniform)
  14357. return;
  14358. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14359. };
  14360. /**
  14361. * Sets a Color4 on a uniform variable
  14362. * @param uniform defines the uniform location
  14363. * @param color4 defines the value to be set
  14364. */
  14365. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14366. if (!uniform)
  14367. return;
  14368. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14369. };
  14370. // States
  14371. /**
  14372. * Set various states to the webGL context
  14373. * @param culling defines backface culling state
  14374. * @param zOffset defines the value to apply to zOffset (0 by default)
  14375. * @param force defines if states must be applied even if cache is up to date
  14376. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14377. */
  14378. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14379. if (zOffset === void 0) { zOffset = 0; }
  14380. if (reverseSide === void 0) { reverseSide = false; }
  14381. // Culling
  14382. if (this._depthCullingState.cull !== culling || force) {
  14383. this._depthCullingState.cull = culling;
  14384. }
  14385. // Cull face
  14386. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14387. if (this._depthCullingState.cullFace !== cullFace || force) {
  14388. this._depthCullingState.cullFace = cullFace;
  14389. }
  14390. // Z offset
  14391. this.setZOffset(zOffset);
  14392. // Front face
  14393. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14394. if (this._depthCullingState.frontFace !== frontFace || force) {
  14395. this._depthCullingState.frontFace = frontFace;
  14396. }
  14397. };
  14398. /**
  14399. * Set the z offset to apply to current rendering
  14400. * @param value defines the offset to apply
  14401. */
  14402. Engine.prototype.setZOffset = function (value) {
  14403. this._depthCullingState.zOffset = value;
  14404. };
  14405. /**
  14406. * Gets the current value of the zOffset
  14407. * @returns the current zOffset state
  14408. */
  14409. Engine.prototype.getZOffset = function () {
  14410. return this._depthCullingState.zOffset;
  14411. };
  14412. /**
  14413. * Enable or disable depth buffering
  14414. * @param enable defines the state to set
  14415. */
  14416. Engine.prototype.setDepthBuffer = function (enable) {
  14417. this._depthCullingState.depthTest = enable;
  14418. };
  14419. /**
  14420. * Gets a boolean indicating if depth writing is enabled
  14421. * @returns the current depth writing state
  14422. */
  14423. Engine.prototype.getDepthWrite = function () {
  14424. return this._depthCullingState.depthMask;
  14425. };
  14426. /**
  14427. * Enable or disable depth writing
  14428. * @param enable defines the state to set
  14429. */
  14430. Engine.prototype.setDepthWrite = function (enable) {
  14431. this._depthCullingState.depthMask = enable;
  14432. };
  14433. /**
  14434. * Enable or disable color writing
  14435. * @param enable defines the state to set
  14436. */
  14437. Engine.prototype.setColorWrite = function (enable) {
  14438. this._gl.colorMask(enable, enable, enable, enable);
  14439. this._colorWrite = enable;
  14440. };
  14441. /**
  14442. * Gets a boolean indicating if color writing is enabled
  14443. * @returns the current color writing state
  14444. */
  14445. Engine.prototype.getColorWrite = function () {
  14446. return this._colorWrite;
  14447. };
  14448. /**
  14449. * Sets alpha constants used by some alpha blending modes
  14450. * @param r defines the red component
  14451. * @param g defines the green component
  14452. * @param b defines the blue component
  14453. * @param a defines the alpha component
  14454. */
  14455. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14456. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14457. };
  14458. /**
  14459. * Sets the current alpha mode
  14460. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14461. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14462. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14463. */
  14464. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14465. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14466. if (this._alphaMode === mode) {
  14467. return;
  14468. }
  14469. switch (mode) {
  14470. case Engine.ALPHA_DISABLE:
  14471. this._alphaState.alphaBlend = false;
  14472. break;
  14473. case Engine.ALPHA_PREMULTIPLIED:
  14474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14475. this._alphaState.alphaBlend = true;
  14476. break;
  14477. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14479. this._alphaState.alphaBlend = true;
  14480. break;
  14481. case Engine.ALPHA_COMBINE:
  14482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14483. this._alphaState.alphaBlend = true;
  14484. break;
  14485. case Engine.ALPHA_ONEONE:
  14486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14487. this._alphaState.alphaBlend = true;
  14488. break;
  14489. case Engine.ALPHA_ADD:
  14490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14491. this._alphaState.alphaBlend = true;
  14492. break;
  14493. case Engine.ALPHA_SUBTRACT:
  14494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14495. this._alphaState.alphaBlend = true;
  14496. break;
  14497. case Engine.ALPHA_MULTIPLY:
  14498. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14499. this._alphaState.alphaBlend = true;
  14500. break;
  14501. case Engine.ALPHA_MAXIMIZED:
  14502. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14503. this._alphaState.alphaBlend = true;
  14504. break;
  14505. case Engine.ALPHA_INTERPOLATE:
  14506. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14507. this._alphaState.alphaBlend = true;
  14508. break;
  14509. case Engine.ALPHA_SCREENMODE:
  14510. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14511. this._alphaState.alphaBlend = true;
  14512. break;
  14513. }
  14514. if (!noDepthWriteChange) {
  14515. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14516. }
  14517. this._alphaMode = mode;
  14518. };
  14519. /**
  14520. * Gets the current alpha mode
  14521. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14522. * @returns the current alpha mode
  14523. */
  14524. Engine.prototype.getAlphaMode = function () {
  14525. return this._alphaMode;
  14526. };
  14527. // Textures
  14528. /**
  14529. * Clears the list of texture accessible through engine.
  14530. * This can help preventing texture load conflict due to name collision.
  14531. */
  14532. Engine.prototype.clearInternalTexturesCache = function () {
  14533. this._internalTexturesCache = [];
  14534. };
  14535. /**
  14536. * Force the entire cache to be cleared
  14537. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14538. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14539. */
  14540. Engine.prototype.wipeCaches = function (bruteForce) {
  14541. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14542. return;
  14543. }
  14544. this._currentEffect = null;
  14545. this._unpackFlipYCached = null;
  14546. this._viewportCached.x = 0;
  14547. this._viewportCached.y = 0;
  14548. this._viewportCached.z = 0;
  14549. this._viewportCached.w = 0;
  14550. if (bruteForce) {
  14551. this.resetTextureCache();
  14552. this._currentProgram = null;
  14553. this._stencilState.reset();
  14554. this._depthCullingState.reset();
  14555. this.setDepthFunctionToLessOrEqual();
  14556. this._alphaState.reset();
  14557. }
  14558. this._resetVertexBufferBinding();
  14559. this._cachedIndexBuffer = null;
  14560. this._cachedEffectForVertexBuffers = null;
  14561. this._unbindVertexArrayObject();
  14562. this.bindIndexBuffer(null);
  14563. };
  14564. /**
  14565. * Set the compressed texture format to use, based on the formats you have, and the formats
  14566. * supported by the hardware / browser.
  14567. *
  14568. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14569. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14570. * to API arguments needed to compressed textures. This puts the burden on the container
  14571. * generator to house the arcane code for determining these for current & future formats.
  14572. *
  14573. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14574. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14575. *
  14576. * Note: The result of this call is not taken into account when a texture is base64.
  14577. *
  14578. * @param formatsAvailable defines the list of those format families you have created
  14579. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14580. *
  14581. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14582. * @returns The extension selected.
  14583. */
  14584. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14585. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14586. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14587. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14588. return this._textureFormatInUse = this._texturesSupported[i];
  14589. }
  14590. }
  14591. }
  14592. // actively set format to nothing, to allow this to be called more than once
  14593. // and possibly fail the 2nd time
  14594. this._textureFormatInUse = null;
  14595. return null;
  14596. };
  14597. /** @hidden */
  14598. Engine.prototype._createTexture = function () {
  14599. var texture = this._gl.createTexture();
  14600. if (!texture) {
  14601. throw new Error("Unable to create texture");
  14602. }
  14603. return texture;
  14604. };
  14605. /**
  14606. * Usually called from BABYLON.Texture.ts.
  14607. * Passed information to create a WebGLTexture
  14608. * @param urlArg defines a value which contains one of the following:
  14609. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14610. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14611. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14612. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14613. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14614. * @param scene needed for loading to the correct scene
  14615. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14616. * @param onLoad optional callback to be called upon successful completion
  14617. * @param onError optional callback to be called upon failure
  14618. * @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
  14619. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14620. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14621. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14622. */
  14623. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14624. var _this = this;
  14625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14626. if (onLoad === void 0) { onLoad = null; }
  14627. if (onError === void 0) { onError = null; }
  14628. if (buffer === void 0) { buffer = null; }
  14629. if (fallback === void 0) { fallback = null; }
  14630. if (format === void 0) { format = null; }
  14631. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14632. var fromData = url.substr(0, 5) === "data:";
  14633. var fromBlob = url.substr(0, 5) === "blob:";
  14634. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14635. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14636. // establish the file extension, if possible
  14637. var lastDot = url.lastIndexOf('.');
  14638. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14639. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14640. var isTGA = (extension.indexOf(".tga") === 0);
  14641. // determine if a ktx file should be substituted
  14642. var isKTX = false;
  14643. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14644. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14645. isKTX = true;
  14646. }
  14647. if (scene) {
  14648. scene._addPendingData(texture);
  14649. }
  14650. texture.url = url;
  14651. texture.generateMipMaps = !noMipmap;
  14652. texture.samplingMode = samplingMode;
  14653. texture.invertY = invertY;
  14654. if (!this._doNotHandleContextLost) {
  14655. // Keep a link to the buffer only if we plan to handle context lost
  14656. texture._buffer = buffer;
  14657. }
  14658. var onLoadObserver = null;
  14659. if (onLoad && !fallback) {
  14660. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14661. }
  14662. if (!fallback)
  14663. this._internalTexturesCache.push(texture);
  14664. var onerror = function (message, exception) {
  14665. if (scene) {
  14666. scene._removePendingData(texture);
  14667. }
  14668. if (onLoadObserver && !isKTX) {
  14669. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14670. texture.onLoadedObservable.remove(onLoadObserver);
  14671. }
  14672. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14673. if (isKTX) {
  14674. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14675. }
  14676. else if (BABYLON.Tools.UseFallbackTexture) {
  14677. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14678. }
  14679. if (onError) {
  14680. onError(message || "Unknown error", exception);
  14681. }
  14682. };
  14683. var callback = null;
  14684. // processing for non-image formats
  14685. if (isKTX || isTGA || isDDS) {
  14686. if (isKTX) {
  14687. callback = function (data) {
  14688. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14689. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14690. ktx.uploadLevels(_this._gl, !noMipmap);
  14691. return false;
  14692. }, samplingMode);
  14693. };
  14694. }
  14695. else if (isTGA) {
  14696. callback = function (arrayBuffer) {
  14697. var data = new Uint8Array(arrayBuffer);
  14698. var header = BABYLON.TGATools.GetTGAHeader(data);
  14699. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14700. BABYLON.TGATools.UploadContent(_this._gl, data);
  14701. return false;
  14702. }, samplingMode);
  14703. };
  14704. }
  14705. else if (isDDS) {
  14706. callback = function (data) {
  14707. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14708. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14709. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14710. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14711. return false;
  14712. }, samplingMode);
  14713. };
  14714. }
  14715. if (!buffer) {
  14716. this._loadFile(url, function (data) {
  14717. if (callback) {
  14718. callback(data);
  14719. }
  14720. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14721. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14722. });
  14723. }
  14724. else {
  14725. if (callback) {
  14726. callback(buffer);
  14727. }
  14728. }
  14729. // image format processing
  14730. }
  14731. else {
  14732. var onload = function (img) {
  14733. if (fromBlob && !_this._doNotHandleContextLost) {
  14734. // We need to store the image if we need to rebuild the texture
  14735. // in case of a webgl context lost
  14736. texture._buffer = img;
  14737. }
  14738. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14739. var gl = _this._gl;
  14740. var isPot = (img.width === potWidth && img.height === potHeight);
  14741. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14742. if (isPot) {
  14743. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14744. return false;
  14745. }
  14746. var maxTextureSize = _this._caps.maxTextureSize;
  14747. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14748. _this._prepareWorkingCanvas();
  14749. if (!_this._workingCanvas || !_this._workingContext) {
  14750. return false;
  14751. }
  14752. _this._workingCanvas.width = potWidth;
  14753. _this._workingCanvas.height = potHeight;
  14754. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14755. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14756. texture.width = potWidth;
  14757. texture.height = potHeight;
  14758. return false;
  14759. }
  14760. else {
  14761. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14762. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14763. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14764. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14766. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14769. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14770. _this._releaseTexture(source_1);
  14771. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14772. continuationCallback();
  14773. });
  14774. }
  14775. return true;
  14776. }, samplingMode);
  14777. };
  14778. if (!fromData || isBase64) {
  14779. if (buffer instanceof HTMLImageElement) {
  14780. onload(buffer);
  14781. }
  14782. else {
  14783. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14784. }
  14785. }
  14786. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14787. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14788. }
  14789. else {
  14790. onload(buffer);
  14791. }
  14792. }
  14793. return texture;
  14794. };
  14795. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14796. var _this = this;
  14797. var rtt = this.createRenderTargetTexture({
  14798. width: destination.width,
  14799. height: destination.height,
  14800. }, {
  14801. generateMipMaps: false,
  14802. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14803. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14804. generateDepthBuffer: false,
  14805. generateStencilBuffer: false
  14806. });
  14807. if (!this._rescalePostProcess) {
  14808. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14809. }
  14810. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14811. _this._rescalePostProcess.onApply = function (effect) {
  14812. effect._bindTexture("textureSampler", source);
  14813. };
  14814. var hostingScene = scene;
  14815. if (!hostingScene) {
  14816. hostingScene = _this.scenes[_this.scenes.length - 1];
  14817. }
  14818. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14819. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14820. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14821. _this.unBindFramebuffer(rtt);
  14822. _this._releaseTexture(rtt);
  14823. if (onComplete) {
  14824. onComplete();
  14825. }
  14826. });
  14827. };
  14828. /**
  14829. * Update a raw texture
  14830. * @param texture defines the texture to update
  14831. * @param data defines the data to store in the texture
  14832. * @param format defines the format of the data
  14833. * @param invertY defines if data must be stored with Y axis inverted
  14834. * @param compression defines the compression used (null by default)
  14835. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14836. */
  14837. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14838. if (compression === void 0) { compression = null; }
  14839. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14840. if (!texture) {
  14841. return;
  14842. }
  14843. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14844. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14845. // babylon's internalFormat but gl's texImage2D format
  14846. var internalFormat = this._getInternalFormat(format);
  14847. var textureType = this._getWebGLTextureType(type);
  14848. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14849. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14850. if (!this._doNotHandleContextLost) {
  14851. texture._bufferView = data;
  14852. texture.format = format;
  14853. texture.type = type;
  14854. texture.invertY = invertY;
  14855. texture._compression = compression;
  14856. }
  14857. if (texture.width % 4 !== 0) {
  14858. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14859. }
  14860. if (compression && data) {
  14861. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14862. }
  14863. else {
  14864. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14865. }
  14866. if (texture.generateMipMaps) {
  14867. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14868. }
  14869. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14870. // this.resetTextureCache();
  14871. texture.isReady = true;
  14872. };
  14873. /**
  14874. * Creates a raw texture
  14875. * @param data defines the data to store in the texture
  14876. * @param width defines the width of the texture
  14877. * @param height defines the height of the texture
  14878. * @param format defines the format of the data
  14879. * @param generateMipMaps defines if the engine should generate the mip levels
  14880. * @param invertY defines if data must be stored with Y axis inverted
  14881. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14882. * @param compression defines the compression used (null by default)
  14883. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14884. * @returns the raw texture inside an InternalTexture
  14885. */
  14886. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14887. if (compression === void 0) { compression = null; }
  14888. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14889. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14890. texture.baseWidth = width;
  14891. texture.baseHeight = height;
  14892. texture.width = width;
  14893. texture.height = height;
  14894. texture.format = format;
  14895. texture.generateMipMaps = generateMipMaps;
  14896. texture.samplingMode = samplingMode;
  14897. texture.invertY = invertY;
  14898. texture._compression = compression;
  14899. texture.type = type;
  14900. if (!this._doNotHandleContextLost) {
  14901. texture._bufferView = data;
  14902. }
  14903. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14904. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14905. // Filters
  14906. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14909. if (generateMipMaps) {
  14910. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14911. }
  14912. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14913. this._internalTexturesCache.push(texture);
  14914. return texture;
  14915. };
  14916. /** @hidden */
  14917. Engine.prototype._unpackFlipY = function (value) {
  14918. if (this._unpackFlipYCached !== value) {
  14919. this._unpackFlipYCached = value;
  14920. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14921. }
  14922. };
  14923. /**
  14924. * Creates a dynamic texture
  14925. * @param width defines the width of the texture
  14926. * @param height defines the height of the texture
  14927. * @param generateMipMaps defines if the engine should generate the mip levels
  14928. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14929. * @returns the dynamic texture inside an InternalTexture
  14930. */
  14931. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14932. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14933. texture.baseWidth = width;
  14934. texture.baseHeight = height;
  14935. if (generateMipMaps) {
  14936. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14937. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14938. }
  14939. // this.resetTextureCache();
  14940. texture.width = width;
  14941. texture.height = height;
  14942. texture.isReady = false;
  14943. texture.generateMipMaps = generateMipMaps;
  14944. texture.samplingMode = samplingMode;
  14945. this.updateTextureSamplingMode(samplingMode, texture);
  14946. this._internalTexturesCache.push(texture);
  14947. return texture;
  14948. };
  14949. /**
  14950. * Update the sampling mode of a given texture
  14951. * @param samplingMode defines the required sampling mode
  14952. * @param texture defines the texture to update
  14953. */
  14954. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14955. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14956. if (texture.isCube) {
  14957. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14958. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14959. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14960. }
  14961. else if (texture.is3D) {
  14962. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14963. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14964. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14965. }
  14966. else {
  14967. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14968. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14969. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14970. }
  14971. texture.samplingMode = samplingMode;
  14972. };
  14973. /**
  14974. * Update the content of a dynamic texture
  14975. * @param texture defines the texture to update
  14976. * @param canvas defines the canvas containing the source
  14977. * @param invertY defines if data must be stored with Y axis inverted
  14978. * @param premulAlpha defines if alpha is stored as premultiplied
  14979. * @param format defines the format of the data
  14980. */
  14981. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14982. if (premulAlpha === void 0) { premulAlpha = false; }
  14983. if (!texture) {
  14984. return;
  14985. }
  14986. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14987. this._unpackFlipY(invertY);
  14988. if (premulAlpha) {
  14989. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14990. }
  14991. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14992. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14993. if (texture.generateMipMaps) {
  14994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14995. }
  14996. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14997. if (premulAlpha) {
  14998. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14999. }
  15000. texture.isReady = true;
  15001. };
  15002. /**
  15003. * Update a video texture
  15004. * @param texture defines the texture to update
  15005. * @param video defines the video element to use
  15006. * @param invertY defines if data must be stored with Y axis inverted
  15007. */
  15008. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15009. if (!texture || texture._isDisabled) {
  15010. return;
  15011. }
  15012. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15013. this._unpackFlipY(!invertY); // Video are upside down by default
  15014. try {
  15015. // Testing video texture support
  15016. if (this._videoTextureSupported === undefined) {
  15017. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15018. if (this._gl.getError() !== 0) {
  15019. this._videoTextureSupported = false;
  15020. }
  15021. else {
  15022. this._videoTextureSupported = true;
  15023. }
  15024. }
  15025. // Copy video through the current working canvas if video texture is not supported
  15026. if (!this._videoTextureSupported) {
  15027. if (!texture._workingCanvas) {
  15028. texture._workingCanvas = document.createElement("canvas");
  15029. var context = texture._workingCanvas.getContext("2d");
  15030. if (!context) {
  15031. throw new Error("Unable to get 2d context");
  15032. }
  15033. texture._workingContext = context;
  15034. texture._workingCanvas.width = texture.width;
  15035. texture._workingCanvas.height = texture.height;
  15036. }
  15037. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15038. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15039. }
  15040. else {
  15041. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15042. }
  15043. if (texture.generateMipMaps) {
  15044. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15045. }
  15046. if (!wasPreviouslyBound) {
  15047. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15048. }
  15049. // this.resetTextureCache();
  15050. texture.isReady = true;
  15051. }
  15052. catch (ex) {
  15053. // Something unexpected
  15054. // Let's disable the texture
  15055. texture._isDisabled = true;
  15056. }
  15057. };
  15058. /**
  15059. * Updates a depth texture Comparison Mode and Function.
  15060. * If the comparison Function is equal to 0, the mode will be set to none.
  15061. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15062. * @param texture The texture to set the comparison function for
  15063. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15064. */
  15065. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15066. if (this.webGLVersion === 1) {
  15067. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15068. return;
  15069. }
  15070. var gl = this._gl;
  15071. if (texture.isCube) {
  15072. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15073. if (comparisonFunction === 0) {
  15074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15076. }
  15077. else {
  15078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15080. }
  15081. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15082. }
  15083. else {
  15084. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15085. if (comparisonFunction === 0) {
  15086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15088. }
  15089. else {
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15092. }
  15093. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15094. }
  15095. texture._comparisonFunction = comparisonFunction;
  15096. };
  15097. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15098. var width = size.width || size;
  15099. var height = size.height || size;
  15100. internalTexture.baseWidth = width;
  15101. internalTexture.baseHeight = height;
  15102. internalTexture.width = width;
  15103. internalTexture.height = height;
  15104. internalTexture.isReady = true;
  15105. internalTexture.samples = 1;
  15106. internalTexture.generateMipMaps = false;
  15107. internalTexture._generateDepthBuffer = true;
  15108. internalTexture._generateStencilBuffer = generateStencil;
  15109. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15110. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15111. internalTexture._comparisonFunction = comparisonFunction;
  15112. var gl = this._gl;
  15113. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15114. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15115. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15116. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15117. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15118. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15119. if (comparisonFunction === 0) {
  15120. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15121. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15122. }
  15123. else {
  15124. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15125. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15126. }
  15127. };
  15128. /**
  15129. * Creates a depth stencil texture.
  15130. * This is only available in WebGL 2 or with the depth texture extension available.
  15131. * @param size The size of face edge in the texture.
  15132. * @param options The options defining the texture.
  15133. * @returns The texture
  15134. */
  15135. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15136. if (options.isCube) {
  15137. var width = size.width || size;
  15138. return this._createDepthStencilCubeTexture(width, options);
  15139. }
  15140. else {
  15141. return this._createDepthStencilTexture(size, options);
  15142. }
  15143. };
  15144. /**
  15145. * Creates a depth stencil texture.
  15146. * This is only available in WebGL 2 or with the depth texture extension available.
  15147. * @param size The size of face edge in the texture.
  15148. * @param options The options defining the texture.
  15149. * @returns The texture
  15150. */
  15151. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15152. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15153. if (!this._caps.depthTextureExtension) {
  15154. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15155. return internalTexture;
  15156. }
  15157. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15158. var gl = this._gl;
  15159. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15160. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15161. if (this.webGLVersion > 1) {
  15162. if (internalOptions.generateStencil) {
  15163. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15164. }
  15165. else {
  15166. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15167. }
  15168. }
  15169. else {
  15170. if (internalOptions.generateStencil) {
  15171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15172. }
  15173. else {
  15174. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15175. }
  15176. }
  15177. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15178. return internalTexture;
  15179. };
  15180. /**
  15181. * Creates a depth stencil cube texture.
  15182. * This is only available in WebGL 2.
  15183. * @param size The size of face edge in the cube texture.
  15184. * @param options The options defining the cube texture.
  15185. * @returns The cube texture
  15186. */
  15187. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15188. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15189. internalTexture.isCube = true;
  15190. if (this.webGLVersion === 1) {
  15191. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15192. return internalTexture;
  15193. }
  15194. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15195. var gl = this._gl;
  15196. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15197. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15198. // Create the depth/stencil buffer
  15199. for (var face = 0; face < 6; face++) {
  15200. if (internalOptions.generateStencil) {
  15201. 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);
  15202. }
  15203. else {
  15204. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15205. }
  15206. }
  15207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15208. return internalTexture;
  15209. };
  15210. /**
  15211. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15212. * @param renderTarget The render target to set the frame buffer for
  15213. */
  15214. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15215. // Create the framebuffer
  15216. var internalTexture = renderTarget.getInternalTexture();
  15217. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15218. return;
  15219. }
  15220. var gl = this._gl;
  15221. var depthStencilTexture = renderTarget.depthStencilTexture;
  15222. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15223. if (depthStencilTexture.isCube) {
  15224. if (depthStencilTexture._generateStencilBuffer) {
  15225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15226. }
  15227. else {
  15228. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15229. }
  15230. }
  15231. else {
  15232. if (depthStencilTexture._generateStencilBuffer) {
  15233. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15234. }
  15235. else {
  15236. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15237. }
  15238. }
  15239. this.bindUnboundFramebuffer(null);
  15240. };
  15241. /**
  15242. * Creates a new render target texture
  15243. * @param size defines the size of the texture
  15244. * @param options defines the options used to create the texture
  15245. * @returns a new render target texture stored in an InternalTexture
  15246. */
  15247. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15248. var fullOptions = new RenderTargetCreationOptions();
  15249. if (options !== undefined && typeof options === "object") {
  15250. fullOptions.generateMipMaps = options.generateMipMaps;
  15251. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15252. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15253. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15254. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15255. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15256. }
  15257. else {
  15258. fullOptions.generateMipMaps = options;
  15259. fullOptions.generateDepthBuffer = true;
  15260. fullOptions.generateStencilBuffer = false;
  15261. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15262. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15263. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15264. }
  15265. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15266. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15267. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15268. }
  15269. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15270. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15271. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15272. }
  15273. var gl = this._gl;
  15274. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15275. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15276. var width = size.width || size;
  15277. var height = size.height || size;
  15278. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15279. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15280. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15281. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15282. }
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15287. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15288. // Create the framebuffer
  15289. var currentFrameBuffer = this._currentFramebuffer;
  15290. var framebuffer = gl.createFramebuffer();
  15291. this.bindUnboundFramebuffer(framebuffer);
  15292. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15293. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15294. if (fullOptions.generateMipMaps) {
  15295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15296. }
  15297. // Unbind
  15298. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15299. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15300. this.bindUnboundFramebuffer(currentFrameBuffer);
  15301. texture._framebuffer = framebuffer;
  15302. texture.baseWidth = width;
  15303. texture.baseHeight = height;
  15304. texture.width = width;
  15305. texture.height = height;
  15306. texture.isReady = true;
  15307. texture.samples = 1;
  15308. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15309. texture.samplingMode = fullOptions.samplingMode;
  15310. texture.type = fullOptions.type;
  15311. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15312. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15313. // this.resetTextureCache();
  15314. this._internalTexturesCache.push(texture);
  15315. return texture;
  15316. };
  15317. /**
  15318. * Create a multi render target texture
  15319. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15320. * @param size defines the size of the texture
  15321. * @param options defines the creation options
  15322. * @returns the cube texture as an InternalTexture
  15323. */
  15324. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15325. var generateMipMaps = false;
  15326. var generateDepthBuffer = true;
  15327. var generateStencilBuffer = false;
  15328. var generateDepthTexture = false;
  15329. var textureCount = 1;
  15330. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15331. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15332. var types = new Array();
  15333. var samplingModes = new Array();
  15334. if (options !== undefined) {
  15335. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15336. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15337. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15338. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15339. textureCount = options.textureCount || 1;
  15340. if (options.types) {
  15341. types = options.types;
  15342. }
  15343. if (options.samplingModes) {
  15344. samplingModes = options.samplingModes;
  15345. }
  15346. }
  15347. var gl = this._gl;
  15348. // Create the framebuffer
  15349. var framebuffer = gl.createFramebuffer();
  15350. this.bindUnboundFramebuffer(framebuffer);
  15351. var width = size.width || size;
  15352. var height = size.height || size;
  15353. var textures = [];
  15354. var attachments = [];
  15355. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15356. for (var i = 0; i < textureCount; i++) {
  15357. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15358. var type = types[i] || defaultType;
  15359. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15360. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15361. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15362. }
  15363. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15364. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15365. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15366. }
  15367. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15368. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15369. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15370. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15371. }
  15372. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15373. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15374. textures.push(texture);
  15375. attachments.push(attachment);
  15376. gl.activeTexture(gl["TEXTURE" + i]);
  15377. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15382. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15383. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15384. if (generateMipMaps) {
  15385. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15386. }
  15387. // Unbind
  15388. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15389. texture._framebuffer = framebuffer;
  15390. texture._depthStencilBuffer = depthStencilBuffer;
  15391. texture.baseWidth = width;
  15392. texture.baseHeight = height;
  15393. texture.width = width;
  15394. texture.height = height;
  15395. texture.isReady = true;
  15396. texture.samples = 1;
  15397. texture.generateMipMaps = generateMipMaps;
  15398. texture.samplingMode = samplingMode;
  15399. texture.type = type;
  15400. texture._generateDepthBuffer = generateDepthBuffer;
  15401. texture._generateStencilBuffer = generateStencilBuffer;
  15402. texture._attachments = attachments;
  15403. this._internalTexturesCache.push(texture);
  15404. }
  15405. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15406. // Depth texture
  15407. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15408. gl.activeTexture(gl.TEXTURE0);
  15409. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15414. 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);
  15415. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15416. depthTexture._framebuffer = framebuffer;
  15417. depthTexture.baseWidth = width;
  15418. depthTexture.baseHeight = height;
  15419. depthTexture.width = width;
  15420. depthTexture.height = height;
  15421. depthTexture.isReady = true;
  15422. depthTexture.samples = 1;
  15423. depthTexture.generateMipMaps = generateMipMaps;
  15424. depthTexture.samplingMode = gl.NEAREST;
  15425. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15426. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15427. textures.push(depthTexture);
  15428. this._internalTexturesCache.push(depthTexture);
  15429. }
  15430. gl.drawBuffers(attachments);
  15431. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15432. this.bindUnboundFramebuffer(null);
  15433. this.resetTextureCache();
  15434. return textures;
  15435. };
  15436. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15437. if (samples === void 0) { samples = 1; }
  15438. var depthStencilBuffer = null;
  15439. var gl = this._gl;
  15440. // Create the depth/stencil buffer
  15441. if (generateStencilBuffer) {
  15442. depthStencilBuffer = gl.createRenderbuffer();
  15443. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15444. if (samples > 1) {
  15445. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15446. }
  15447. else {
  15448. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15449. }
  15450. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15451. }
  15452. else if (generateDepthBuffer) {
  15453. depthStencilBuffer = gl.createRenderbuffer();
  15454. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15455. if (samples > 1) {
  15456. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15457. }
  15458. else {
  15459. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15460. }
  15461. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15462. }
  15463. return depthStencilBuffer;
  15464. };
  15465. /**
  15466. * Updates the sample count of a render target texture
  15467. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15468. * @param texture defines the texture to update
  15469. * @param samples defines the sample count to set
  15470. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15471. */
  15472. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15473. if (this.webGLVersion < 2 || !texture) {
  15474. return 1;
  15475. }
  15476. if (texture.samples === samples) {
  15477. return samples;
  15478. }
  15479. var gl = this._gl;
  15480. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15481. // Dispose previous render buffers
  15482. if (texture._depthStencilBuffer) {
  15483. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15484. texture._depthStencilBuffer = null;
  15485. }
  15486. if (texture._MSAAFramebuffer) {
  15487. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15488. texture._MSAAFramebuffer = null;
  15489. }
  15490. if (texture._MSAARenderBuffer) {
  15491. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15492. texture._MSAARenderBuffer = null;
  15493. }
  15494. if (samples > 1) {
  15495. var framebuffer = gl.createFramebuffer();
  15496. if (!framebuffer) {
  15497. throw new Error("Unable to create multi sampled framebuffer");
  15498. }
  15499. texture._MSAAFramebuffer = framebuffer;
  15500. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15501. var colorRenderbuffer = gl.createRenderbuffer();
  15502. if (!colorRenderbuffer) {
  15503. throw new Error("Unable to create multi sampled framebuffer");
  15504. }
  15505. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15506. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15507. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15508. texture._MSAARenderBuffer = colorRenderbuffer;
  15509. }
  15510. else {
  15511. this.bindUnboundFramebuffer(texture._framebuffer);
  15512. }
  15513. texture.samples = samples;
  15514. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15515. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15516. this.bindUnboundFramebuffer(null);
  15517. return samples;
  15518. };
  15519. /**
  15520. * Update the sample count for a given multiple render target texture
  15521. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15522. * @param textures defines the textures to update
  15523. * @param samples defines the sample count to set
  15524. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15525. */
  15526. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15527. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15528. return 1;
  15529. }
  15530. if (textures[0].samples === samples) {
  15531. return samples;
  15532. }
  15533. var gl = this._gl;
  15534. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15535. // Dispose previous render buffers
  15536. if (textures[0]._depthStencilBuffer) {
  15537. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15538. textures[0]._depthStencilBuffer = null;
  15539. }
  15540. if (textures[0]._MSAAFramebuffer) {
  15541. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15542. textures[0]._MSAAFramebuffer = null;
  15543. }
  15544. for (var i = 0; i < textures.length; i++) {
  15545. if (textures[i]._MSAARenderBuffer) {
  15546. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15547. textures[i]._MSAARenderBuffer = null;
  15548. }
  15549. }
  15550. if (samples > 1) {
  15551. var framebuffer = gl.createFramebuffer();
  15552. if (!framebuffer) {
  15553. throw new Error("Unable to create multi sampled framebuffer");
  15554. }
  15555. this.bindUnboundFramebuffer(framebuffer);
  15556. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15557. var attachments = [];
  15558. for (var i = 0; i < textures.length; i++) {
  15559. var texture = textures[i];
  15560. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15561. var colorRenderbuffer = gl.createRenderbuffer();
  15562. if (!colorRenderbuffer) {
  15563. throw new Error("Unable to create multi sampled framebuffer");
  15564. }
  15565. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15566. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15567. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15568. texture._MSAAFramebuffer = framebuffer;
  15569. texture._MSAARenderBuffer = colorRenderbuffer;
  15570. texture.samples = samples;
  15571. texture._depthStencilBuffer = depthStencilBuffer;
  15572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15573. attachments.push(attachment);
  15574. }
  15575. gl.drawBuffers(attachments);
  15576. }
  15577. else {
  15578. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15579. }
  15580. this.bindUnboundFramebuffer(null);
  15581. return samples;
  15582. };
  15583. /** @hidden */
  15584. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15585. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15586. };
  15587. /** @hidden */
  15588. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15589. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15590. };
  15591. /** @hidden */
  15592. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15593. var gl = this._gl;
  15594. var textureType = this._getWebGLTextureType(texture.type);
  15595. var format = this._getInternalFormat(texture.format);
  15596. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15597. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15598. this._bindTextureDirectly(bindTarget, texture, true);
  15599. this._unpackFlipY(texture.invertY);
  15600. var target = gl.TEXTURE_2D;
  15601. if (texture.isCube) {
  15602. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15603. }
  15604. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15605. this._bindTextureDirectly(bindTarget, null, true);
  15606. };
  15607. /**
  15608. * Creates a new render target cube texture
  15609. * @param size defines the size of the texture
  15610. * @param options defines the options used to create the texture
  15611. * @returns a new render target cube texture stored in an InternalTexture
  15612. */
  15613. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15614. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15615. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15616. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15617. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15618. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15619. }
  15620. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15621. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15622. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15623. }
  15624. var gl = this._gl;
  15625. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15626. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15627. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15628. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15629. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15630. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15631. }
  15632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15636. for (var face = 0; face < 6; face++) {
  15637. 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);
  15638. }
  15639. // Create the framebuffer
  15640. var framebuffer = gl.createFramebuffer();
  15641. this.bindUnboundFramebuffer(framebuffer);
  15642. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15643. // MipMaps
  15644. if (fullOptions.generateMipMaps) {
  15645. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15646. }
  15647. // Unbind
  15648. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15649. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15650. this.bindUnboundFramebuffer(null);
  15651. texture._framebuffer = framebuffer;
  15652. texture.width = size;
  15653. texture.height = size;
  15654. texture.isReady = true;
  15655. texture.isCube = true;
  15656. texture.samples = 1;
  15657. texture.generateMipMaps = fullOptions.generateMipMaps;
  15658. texture.samplingMode = fullOptions.samplingMode;
  15659. texture.type = fullOptions.type;
  15660. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15661. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15662. this._internalTexturesCache.push(texture);
  15663. return texture;
  15664. };
  15665. /**
  15666. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15667. * @param rootUrl defines the url where the file to load is located
  15668. * @param scene defines the current scene
  15669. * @param lodScale defines scale to apply to the mip map selection
  15670. * @param lodOffset defines offset to apply to the mip map selection
  15671. * @param onLoad defines an optional callback raised when the texture is loaded
  15672. * @param onError defines an optional callback raised if there is an issue to load the texture
  15673. * @param format defines the format of the data
  15674. * @param forcedExtension defines the extension to use to pick the right loader
  15675. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15676. * @returns the cube texture as an InternalTexture
  15677. */
  15678. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15679. var _this = this;
  15680. if (onLoad === void 0) { onLoad = null; }
  15681. if (onError === void 0) { onError = null; }
  15682. if (forcedExtension === void 0) { forcedExtension = null; }
  15683. if (createPolynomials === void 0) { createPolynomials = true; }
  15684. var callback = function (loadData) {
  15685. if (!loadData) {
  15686. if (onLoad) {
  15687. onLoad(null);
  15688. }
  15689. return;
  15690. }
  15691. var texture = loadData.texture;
  15692. if (!createPolynomials) {
  15693. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15694. }
  15695. else if (loadData.info.sphericalPolynomial) {
  15696. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15697. }
  15698. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15699. if (_this._caps.textureLOD) {
  15700. // Do not add extra process if texture lod is supported.
  15701. if (onLoad) {
  15702. onLoad(texture);
  15703. }
  15704. return;
  15705. }
  15706. var mipSlices = 3;
  15707. var gl = _this._gl;
  15708. var width = loadData.width;
  15709. if (!width) {
  15710. return;
  15711. }
  15712. var textures = [];
  15713. for (var i = 0; i < mipSlices; i++) {
  15714. //compute LOD from even spacing in smoothness (matching shader calculation)
  15715. var smoothness = i / (mipSlices - 1);
  15716. var roughness = 1 - smoothness;
  15717. var minLODIndex = lodOffset; // roughness = 0
  15718. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15719. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15720. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15721. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15722. glTextureFromLod.isCube = true;
  15723. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15728. if (loadData.isDDS) {
  15729. var info = loadData.info;
  15730. var data = loadData.data;
  15731. _this._unpackFlipY(info.isCompressed);
  15732. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15733. }
  15734. else {
  15735. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15736. }
  15737. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15738. // Wrap in a base texture for easy binding.
  15739. var lodTexture = new BABYLON.BaseTexture(scene);
  15740. lodTexture.isCube = true;
  15741. lodTexture._texture = glTextureFromLod;
  15742. glTextureFromLod.isReady = true;
  15743. textures.push(lodTexture);
  15744. }
  15745. texture._lodTextureHigh = textures[2];
  15746. texture._lodTextureMid = textures[1];
  15747. texture._lodTextureLow = textures[0];
  15748. if (onLoad) {
  15749. onLoad(texture);
  15750. }
  15751. };
  15752. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15753. };
  15754. /**
  15755. * Creates a cube texture
  15756. * @param rootUrl defines the url where the files to load is located
  15757. * @param scene defines the current scene
  15758. * @param files defines the list of files to load (1 per face)
  15759. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15760. * @param onLoad defines an optional callback raised when the texture is loaded
  15761. * @param onError defines an optional callback raised if there is an issue to load the texture
  15762. * @param format defines the format of the data
  15763. * @param forcedExtension defines the extension to use to pick the right loader
  15764. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15765. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15766. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15767. * @returns the cube texture as an InternalTexture
  15768. */
  15769. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15770. var _this = this;
  15771. if (onLoad === void 0) { onLoad = null; }
  15772. if (onError === void 0) { onError = null; }
  15773. if (forcedExtension === void 0) { forcedExtension = null; }
  15774. if (createPolynomials === void 0) { createPolynomials = false; }
  15775. if (lodScale === void 0) { lodScale = 0; }
  15776. if (lodOffset === void 0) { lodOffset = 0; }
  15777. var gl = this._gl;
  15778. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15779. texture.isCube = true;
  15780. texture.url = rootUrl;
  15781. texture.generateMipMaps = !noMipmap;
  15782. texture._lodGenerationScale = lodScale;
  15783. texture._lodGenerationOffset = lodOffset;
  15784. if (!this._doNotHandleContextLost) {
  15785. texture._extension = forcedExtension;
  15786. texture._files = files;
  15787. }
  15788. var isKTX = false;
  15789. var isDDS = false;
  15790. var isEnv = false;
  15791. var lastDot = rootUrl.lastIndexOf('.');
  15792. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15793. if (this._textureFormatInUse) {
  15794. extension = this._textureFormatInUse;
  15795. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15796. isKTX = true;
  15797. }
  15798. else {
  15799. isDDS = (extension === ".dds");
  15800. isEnv = (extension === ".env");
  15801. }
  15802. var onerror = function (request, exception) {
  15803. if (onError && request) {
  15804. onError(request.status + " " + request.statusText, exception);
  15805. }
  15806. };
  15807. if (isKTX) {
  15808. this._loadFile(rootUrl, function (data) {
  15809. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15810. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15811. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15812. _this._unpackFlipY(true);
  15813. ktx.uploadLevels(_this._gl, !noMipmap);
  15814. _this.setCubeMapTextureParams(gl, loadMipmap);
  15815. texture.width = ktx.pixelWidth;
  15816. texture.height = ktx.pixelHeight;
  15817. texture.isReady = true;
  15818. }, undefined, undefined, true, onerror);
  15819. }
  15820. else if (isEnv) {
  15821. this._loadFile(rootUrl, function (data) {
  15822. data = data;
  15823. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15824. if (info) {
  15825. texture.width = info.width;
  15826. texture.height = info.width;
  15827. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15828. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15829. texture.isReady = true;
  15830. if (onLoad) {
  15831. onLoad();
  15832. }
  15833. });
  15834. }
  15835. else if (onError) {
  15836. onError("Can not parse the environment file", null);
  15837. }
  15838. }, undefined, undefined, true, onerror);
  15839. }
  15840. else if (isDDS) {
  15841. if (files && files.length === 6) {
  15842. this._cascadeLoadFiles(scene, function (imgs) {
  15843. var info;
  15844. var loadMipmap = false;
  15845. var width = 0;
  15846. for (var index = 0; index < imgs.length; index++) {
  15847. var data = imgs[index];
  15848. info = BABYLON.DDSTools.GetDDSInfo(data);
  15849. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15850. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15851. _this._unpackFlipY(info.isCompressed);
  15852. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15853. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15854. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15855. }
  15856. texture.width = info.width;
  15857. texture.height = info.height;
  15858. texture.type = info.textureType;
  15859. width = info.width;
  15860. }
  15861. _this.setCubeMapTextureParams(gl, loadMipmap);
  15862. texture.isReady = true;
  15863. if (onLoad) {
  15864. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15865. }
  15866. }, files, onError);
  15867. }
  15868. else {
  15869. this._loadFile(rootUrl, function (data) {
  15870. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15871. if (createPolynomials) {
  15872. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15873. }
  15874. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15875. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15876. _this._unpackFlipY(info.isCompressed);
  15877. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15878. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15879. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15880. }
  15881. _this.setCubeMapTextureParams(gl, loadMipmap);
  15882. texture.width = info.width;
  15883. texture.height = info.height;
  15884. texture.isReady = true;
  15885. texture.type = info.textureType;
  15886. if (onLoad) {
  15887. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15888. }
  15889. }, undefined, undefined, true, onerror);
  15890. }
  15891. }
  15892. else {
  15893. if (!files) {
  15894. throw new Error("Cannot load cubemap because files were not defined");
  15895. }
  15896. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15897. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15898. var height = width;
  15899. _this._prepareWorkingCanvas();
  15900. if (!_this._workingCanvas || !_this._workingContext) {
  15901. return;
  15902. }
  15903. _this._workingCanvas.width = width;
  15904. _this._workingCanvas.height = height;
  15905. var faces = [
  15906. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15907. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15908. ];
  15909. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15910. _this._unpackFlipY(false);
  15911. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15912. for (var index = 0; index < faces.length; index++) {
  15913. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15914. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15915. }
  15916. if (!noMipmap) {
  15917. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15918. }
  15919. _this.setCubeMapTextureParams(gl, !noMipmap);
  15920. texture.width = width;
  15921. texture.height = height;
  15922. texture.isReady = true;
  15923. if (format) {
  15924. texture.format = format;
  15925. }
  15926. texture.onLoadedObservable.notifyObservers(texture);
  15927. texture.onLoadedObservable.clear();
  15928. if (onLoad) {
  15929. onLoad();
  15930. }
  15931. }, files, onError);
  15932. }
  15933. this._internalTexturesCache.push(texture);
  15934. return texture;
  15935. };
  15936. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15941. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15942. // this.resetTextureCache();
  15943. };
  15944. /**
  15945. * Update a raw cube texture
  15946. * @param texture defines the texture to udpdate
  15947. * @param data defines the data to store
  15948. * @param format defines the data format
  15949. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15950. * @param invertY defines if data must be stored with Y axis inverted
  15951. * @param compression defines the compression used (null by default)
  15952. * @param level defines which level of the texture to update
  15953. */
  15954. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15955. if (compression === void 0) { compression = null; }
  15956. if (level === void 0) { level = 0; }
  15957. texture._bufferViewArray = data;
  15958. texture.format = format;
  15959. texture.type = type;
  15960. texture.invertY = invertY;
  15961. texture._compression = compression;
  15962. var gl = this._gl;
  15963. var textureType = this._getWebGLTextureType(type);
  15964. var internalFormat = this._getInternalFormat(format);
  15965. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15966. var needConversion = false;
  15967. if (internalFormat === gl.RGB) {
  15968. internalFormat = gl.RGBA;
  15969. needConversion = true;
  15970. }
  15971. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15972. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15973. if (texture.width % 4 !== 0) {
  15974. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15975. }
  15976. // Data are known to be in +X +Y +Z -X -Y -Z
  15977. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15978. var faceData = data[faceIndex];
  15979. if (compression) {
  15980. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15981. }
  15982. else {
  15983. if (needConversion) {
  15984. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15985. }
  15986. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15987. }
  15988. }
  15989. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15990. if (isPot && texture.generateMipMaps && level === 0) {
  15991. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15992. }
  15993. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15994. // this.resetTextureCache();
  15995. texture.isReady = true;
  15996. };
  15997. /**
  15998. * Creates a new raw cube texture
  15999. * @param data defines the array of data to use to create each face
  16000. * @param size defines the size of the textures
  16001. * @param format defines the format of the data
  16002. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16003. * @param generateMipMaps defines if the engine should generate the mip levels
  16004. * @param invertY defines if data must be stored with Y axis inverted
  16005. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16006. * @param compression defines the compression used (null by default)
  16007. * @returns the cube texture as an InternalTexture
  16008. */
  16009. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16010. if (compression === void 0) { compression = null; }
  16011. var gl = this._gl;
  16012. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16013. texture.isCube = true;
  16014. texture.generateMipMaps = generateMipMaps;
  16015. texture.format = format;
  16016. texture.type = type;
  16017. if (!this._doNotHandleContextLost) {
  16018. texture._bufferViewArray = data;
  16019. }
  16020. var textureType = this._getWebGLTextureType(type);
  16021. var internalFormat = this._getInternalFormat(format);
  16022. if (internalFormat === gl.RGB) {
  16023. internalFormat = gl.RGBA;
  16024. }
  16025. var width = size;
  16026. var height = width;
  16027. texture.width = width;
  16028. texture.height = height;
  16029. // Double check on POT to generate Mips.
  16030. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16031. if (!isPot) {
  16032. generateMipMaps = false;
  16033. }
  16034. // Upload data if needed. The texture won't be ready until then.
  16035. if (data) {
  16036. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16037. }
  16038. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16039. // Filters
  16040. if (data && generateMipMaps) {
  16041. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16042. }
  16043. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16046. }
  16047. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16050. }
  16051. else {
  16052. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16055. }
  16056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16058. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16059. return texture;
  16060. };
  16061. /**
  16062. * Creates a new raw cube texture from a specified url
  16063. * @param url defines the url where the data is located
  16064. * @param scene defines the current scene
  16065. * @param size defines the size of the textures
  16066. * @param format defines the format of the data
  16067. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16068. * @param noMipmap defines if the engine should avoid generating the mip levels
  16069. * @param callback defines a callback used to extract texture data from loaded data
  16070. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16071. * @param onLoad defines a callback called when texture is loaded
  16072. * @param onError defines a callback called if there is an error
  16073. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16074. * @param invertY defines if data must be stored with Y axis inverted
  16075. * @returns the cube texture as an InternalTexture
  16076. */
  16077. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16078. var _this = this;
  16079. if (onLoad === void 0) { onLoad = null; }
  16080. if (onError === void 0) { onError = null; }
  16081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16082. if (invertY === void 0) { invertY = false; }
  16083. var gl = this._gl;
  16084. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16085. scene._addPendingData(texture);
  16086. texture.url = url;
  16087. this._internalTexturesCache.push(texture);
  16088. var onerror = function (request, exception) {
  16089. scene._removePendingData(texture);
  16090. if (onError && request) {
  16091. onError(request.status + " " + request.statusText, exception);
  16092. }
  16093. };
  16094. var internalCallback = function (data) {
  16095. var width = texture.width;
  16096. var faceDataArrays = callback(data);
  16097. if (!faceDataArrays) {
  16098. return;
  16099. }
  16100. if (mipmapGenerator) {
  16101. var textureType = _this._getWebGLTextureType(type);
  16102. var internalFormat = _this._getInternalFormat(format);
  16103. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16104. var needConversion = false;
  16105. if (internalFormat === gl.RGB) {
  16106. internalFormat = gl.RGBA;
  16107. needConversion = true;
  16108. }
  16109. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16110. _this._unpackFlipY(false);
  16111. var mipData = mipmapGenerator(faceDataArrays);
  16112. for (var level = 0; level < mipData.length; level++) {
  16113. var mipSize = width >> level;
  16114. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16115. var mipFaceData = mipData[level][faceIndex];
  16116. if (needConversion) {
  16117. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16118. }
  16119. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16120. }
  16121. }
  16122. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16123. }
  16124. else {
  16125. texture.generateMipMaps = !noMipmap;
  16126. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16127. }
  16128. texture.isReady = true;
  16129. // this.resetTextureCache();
  16130. scene._removePendingData(texture);
  16131. if (onLoad) {
  16132. onLoad();
  16133. }
  16134. };
  16135. this._loadFile(url, function (data) {
  16136. internalCallback(data);
  16137. }, undefined, scene.database, true, onerror);
  16138. return texture;
  16139. };
  16140. ;
  16141. /**
  16142. * Update a raw 3D texture
  16143. * @param texture defines the texture to update
  16144. * @param data defines the data to store
  16145. * @param format defines the data format
  16146. * @param invertY defines if data must be stored with Y axis inverted
  16147. * @param compression defines the used compression (can be null)
  16148. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16149. */
  16150. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16151. if (compression === void 0) { compression = null; }
  16152. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16153. var internalType = this._getWebGLTextureType(textureType);
  16154. var internalFormat = this._getInternalFormat(format);
  16155. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16156. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16157. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16158. if (!this._doNotHandleContextLost) {
  16159. texture._bufferView = data;
  16160. texture.format = format;
  16161. texture.invertY = invertY;
  16162. texture._compression = compression;
  16163. }
  16164. if (texture.width % 4 !== 0) {
  16165. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16166. }
  16167. if (compression && data) {
  16168. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16169. }
  16170. else {
  16171. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16172. }
  16173. if (texture.generateMipMaps) {
  16174. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16175. }
  16176. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16177. // this.resetTextureCache();
  16178. texture.isReady = true;
  16179. };
  16180. /**
  16181. * Creates a new raw 3D texture
  16182. * @param data defines the data used to create the texture
  16183. * @param width defines the width of the texture
  16184. * @param height defines the height of the texture
  16185. * @param depth defines the depth of the texture
  16186. * @param format defines the format of the texture
  16187. * @param generateMipMaps defines if the engine must generate mip levels
  16188. * @param invertY defines if data must be stored with Y axis inverted
  16189. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16190. * @param compression defines the compressed used (can be null)
  16191. * @param textureType defines the compressed used (can be null)
  16192. * @returns a new raw 3D texture (stored in an InternalTexture)
  16193. */
  16194. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16195. if (compression === void 0) { compression = null; }
  16196. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16197. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16198. texture.baseWidth = width;
  16199. texture.baseHeight = height;
  16200. texture.baseDepth = depth;
  16201. texture.width = width;
  16202. texture.height = height;
  16203. texture.depth = depth;
  16204. texture.format = format;
  16205. texture.type = textureType;
  16206. texture.generateMipMaps = generateMipMaps;
  16207. texture.samplingMode = samplingMode;
  16208. texture.is3D = true;
  16209. if (!this._doNotHandleContextLost) {
  16210. texture._bufferView = data;
  16211. }
  16212. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16213. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16214. // Filters
  16215. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16216. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16217. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16218. if (generateMipMaps) {
  16219. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16220. }
  16221. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16222. this._internalTexturesCache.push(texture);
  16223. return texture;
  16224. };
  16225. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16226. var gl = this._gl;
  16227. if (!gl) {
  16228. return;
  16229. }
  16230. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16231. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16233. if (!noMipmap && !isCompressed) {
  16234. gl.generateMipmap(gl.TEXTURE_2D);
  16235. }
  16236. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16237. // this.resetTextureCache();
  16238. if (scene) {
  16239. scene._removePendingData(texture);
  16240. }
  16241. texture.onLoadedObservable.notifyObservers(texture);
  16242. texture.onLoadedObservable.clear();
  16243. };
  16244. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16245. var _this = this;
  16246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16247. var maxTextureSize = this.getCaps().maxTextureSize;
  16248. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16249. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16250. var gl = this._gl;
  16251. if (!gl) {
  16252. return;
  16253. }
  16254. if (!texture._webGLTexture) {
  16255. // this.resetTextureCache();
  16256. if (scene) {
  16257. scene._removePendingData(texture);
  16258. }
  16259. return;
  16260. }
  16261. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16262. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16263. texture.baseWidth = width;
  16264. texture.baseHeight = height;
  16265. texture.width = potWidth;
  16266. texture.height = potHeight;
  16267. texture.isReady = true;
  16268. if (processFunction(potWidth, potHeight, function () {
  16269. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16270. })) {
  16271. // Returning as texture needs extra async steps
  16272. return;
  16273. }
  16274. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16275. };
  16276. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16277. // Create new RGBA data container.
  16278. var rgbaData;
  16279. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16280. rgbaData = new Float32Array(width * height * 4);
  16281. }
  16282. else {
  16283. rgbaData = new Uint32Array(width * height * 4);
  16284. }
  16285. // Convert each pixel.
  16286. for (var x = 0; x < width; x++) {
  16287. for (var y = 0; y < height; y++) {
  16288. var index = (y * width + x) * 3;
  16289. var newIndex = (y * width + x) * 4;
  16290. // Map Old Value to new value.
  16291. rgbaData[newIndex + 0] = rgbData[index + 0];
  16292. rgbaData[newIndex + 1] = rgbData[index + 1];
  16293. rgbaData[newIndex + 2] = rgbData[index + 2];
  16294. // Add fully opaque alpha channel.
  16295. rgbaData[newIndex + 3] = 1;
  16296. }
  16297. }
  16298. return rgbaData;
  16299. };
  16300. /** @hidden */
  16301. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16302. var gl = this._gl;
  16303. if (texture._framebuffer) {
  16304. gl.deleteFramebuffer(texture._framebuffer);
  16305. texture._framebuffer = null;
  16306. }
  16307. if (texture._depthStencilBuffer) {
  16308. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16309. texture._depthStencilBuffer = null;
  16310. }
  16311. if (texture._MSAAFramebuffer) {
  16312. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16313. texture._MSAAFramebuffer = null;
  16314. }
  16315. if (texture._MSAARenderBuffer) {
  16316. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16317. texture._MSAARenderBuffer = null;
  16318. }
  16319. };
  16320. /** @hidden */
  16321. Engine.prototype._releaseTexture = function (texture) {
  16322. var gl = this._gl;
  16323. this._releaseFramebufferObjects(texture);
  16324. gl.deleteTexture(texture._webGLTexture);
  16325. // Unbind channels
  16326. this.unbindAllTextures();
  16327. var index = this._internalTexturesCache.indexOf(texture);
  16328. if (index !== -1) {
  16329. this._internalTexturesCache.splice(index, 1);
  16330. }
  16331. // Integrated fixed lod samplers.
  16332. if (texture._lodTextureHigh) {
  16333. texture._lodTextureHigh.dispose();
  16334. }
  16335. if (texture._lodTextureMid) {
  16336. texture._lodTextureMid.dispose();
  16337. }
  16338. if (texture._lodTextureLow) {
  16339. texture._lodTextureLow.dispose();
  16340. }
  16341. // Set output texture of post process to null if the texture has been released/disposed
  16342. this.scenes.forEach(function (scene) {
  16343. scene.postProcesses.forEach(function (postProcess) {
  16344. if (postProcess._outputTexture == texture) {
  16345. postProcess._outputTexture = null;
  16346. }
  16347. });
  16348. scene.cameras.forEach(function (camera) {
  16349. camera._postProcesses.forEach(function (postProcess) {
  16350. if (postProcess) {
  16351. if (postProcess._outputTexture == texture) {
  16352. postProcess._outputTexture = null;
  16353. }
  16354. }
  16355. });
  16356. });
  16357. });
  16358. };
  16359. Engine.prototype.setProgram = function (program) {
  16360. if (this._currentProgram !== program) {
  16361. this._gl.useProgram(program);
  16362. this._currentProgram = program;
  16363. }
  16364. };
  16365. /**
  16366. * Binds an effect to the webGL context
  16367. * @param effect defines the effect to bind
  16368. */
  16369. Engine.prototype.bindSamplers = function (effect) {
  16370. this.setProgram(effect.getProgram());
  16371. var samplers = effect.getSamplers();
  16372. for (var index = 0; index < samplers.length; index++) {
  16373. var uniform = effect.getUniform(samplers[index]);
  16374. if (uniform) {
  16375. this._boundUniforms[index] = uniform;
  16376. }
  16377. }
  16378. this._currentEffect = null;
  16379. };
  16380. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16381. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16382. return;
  16383. }
  16384. // Remove
  16385. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16386. // Bind last to it
  16387. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16388. // Bind to dummy
  16389. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16390. };
  16391. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16392. if (!internalTexture) {
  16393. return -1;
  16394. }
  16395. internalTexture._initialSlot = channel;
  16396. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16397. if (channel !== internalTexture._designatedSlot) {
  16398. this._textureCollisions.addCount(1, false);
  16399. }
  16400. }
  16401. else {
  16402. if (channel !== internalTexture._designatedSlot) {
  16403. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16404. return internalTexture._designatedSlot;
  16405. }
  16406. else {
  16407. // No slot for this texture, let's pick a new one (if we find a free slot)
  16408. if (this._nextFreeTextureSlots.length) {
  16409. return this._nextFreeTextureSlots[0];
  16410. }
  16411. // We need to recycle the oldest bound texture, sorry.
  16412. this._textureCollisions.addCount(1, false);
  16413. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16414. }
  16415. }
  16416. }
  16417. return channel;
  16418. };
  16419. Engine.prototype._linkTrackers = function (previous, next) {
  16420. previous.next = next;
  16421. next.previous = previous;
  16422. };
  16423. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16424. var currentSlot = internalTexture._designatedSlot;
  16425. if (currentSlot === -1) {
  16426. return -1;
  16427. }
  16428. internalTexture._designatedSlot = -1;
  16429. if (this.disableTextureBindingOptimization) {
  16430. return -1;
  16431. }
  16432. // Remove from bound list
  16433. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16434. // Free the slot
  16435. this._boundTexturesCache[currentSlot] = null;
  16436. this._nextFreeTextureSlots.push(currentSlot);
  16437. return currentSlot;
  16438. };
  16439. Engine.prototype._activateCurrentTexture = function () {
  16440. if (this._currentTextureChannel !== this._activeChannel) {
  16441. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16442. this._currentTextureChannel = this._activeChannel;
  16443. }
  16444. };
  16445. /** @hidden */
  16446. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16447. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16448. if (force === void 0) { force = false; }
  16449. var wasPreviouslyBound = false;
  16450. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16451. this._activeChannel = texture._designatedSlot;
  16452. }
  16453. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16454. var isTextureForRendering = texture && texture._initialSlot > -1;
  16455. if (currentTextureBound !== texture || force) {
  16456. if (currentTextureBound) {
  16457. this._removeDesignatedSlot(currentTextureBound);
  16458. }
  16459. this._activateCurrentTexture();
  16460. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16461. this._boundTexturesCache[this._activeChannel] = texture;
  16462. if (texture) {
  16463. if (!this.disableTextureBindingOptimization) {
  16464. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16465. if (slotIndex > -1) {
  16466. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16467. }
  16468. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16469. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16470. }
  16471. texture._designatedSlot = this._activeChannel;
  16472. }
  16473. }
  16474. else if (forTextureDataUpdate) {
  16475. wasPreviouslyBound = true;
  16476. this._activateCurrentTexture();
  16477. }
  16478. if (isTextureForRendering && !forTextureDataUpdate) {
  16479. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16480. }
  16481. return wasPreviouslyBound;
  16482. };
  16483. /** @hidden */
  16484. Engine.prototype._bindTexture = function (channel, texture) {
  16485. if (channel < 0) {
  16486. return;
  16487. }
  16488. if (texture) {
  16489. channel = this._getCorrectTextureChannel(channel, texture);
  16490. }
  16491. this._activeChannel = channel;
  16492. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16493. };
  16494. /**
  16495. * Sets a texture to the webGL context from a postprocess
  16496. * @param channel defines the channel to use
  16497. * @param postProcess defines the source postprocess
  16498. */
  16499. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16500. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16501. };
  16502. /**
  16503. * Binds the output of the passed in post process to the texture channel specified
  16504. * @param channel The channel the texture should be bound to
  16505. * @param postProcess The post process which's output should be bound
  16506. */
  16507. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16508. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16509. };
  16510. /**
  16511. * Unbind all textures from the webGL context
  16512. */
  16513. Engine.prototype.unbindAllTextures = function () {
  16514. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16515. this._activeChannel = channel;
  16516. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16517. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16518. if (this.webGLVersion > 1) {
  16519. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16520. }
  16521. }
  16522. };
  16523. /**
  16524. * Sets a texture to the according uniform.
  16525. * @param channel The texture channel
  16526. * @param uniform The uniform to set
  16527. * @param texture The texture to apply
  16528. */
  16529. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16530. if (channel < 0) {
  16531. return;
  16532. }
  16533. if (uniform) {
  16534. this._boundUniforms[channel] = uniform;
  16535. }
  16536. this._setTexture(channel, texture);
  16537. };
  16538. /**
  16539. * Sets a depth stencil texture from a render target to the according uniform.
  16540. * @param channel The texture channel
  16541. * @param uniform The uniform to set
  16542. * @param texture The render target texture containing the depth stencil texture to apply
  16543. */
  16544. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16545. if (channel < 0) {
  16546. return;
  16547. }
  16548. if (uniform) {
  16549. this._boundUniforms[channel] = uniform;
  16550. }
  16551. if (!texture || !texture.depthStencilTexture) {
  16552. this._setTexture(channel, null);
  16553. }
  16554. else {
  16555. this._setTexture(channel, texture, false, true);
  16556. }
  16557. };
  16558. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16559. var uniform = this._boundUniforms[sourceSlot];
  16560. if (uniform._currentState === destination) {
  16561. return;
  16562. }
  16563. this._gl.uniform1i(uniform, destination);
  16564. uniform._currentState = destination;
  16565. };
  16566. Engine.prototype._getTextureWrapMode = function (mode) {
  16567. switch (mode) {
  16568. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16569. return this._gl.REPEAT;
  16570. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16571. return this._gl.CLAMP_TO_EDGE;
  16572. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16573. return this._gl.MIRRORED_REPEAT;
  16574. }
  16575. return this._gl.REPEAT;
  16576. };
  16577. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16578. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16579. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16580. // Not ready?
  16581. if (!texture) {
  16582. if (this._boundTexturesCache[channel] != null) {
  16583. this._activeChannel = channel;
  16584. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16585. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16586. if (this.webGLVersion > 1) {
  16587. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16588. }
  16589. }
  16590. return false;
  16591. }
  16592. // Video
  16593. if (texture.video) {
  16594. this._activeChannel = channel;
  16595. texture.update();
  16596. }
  16597. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16598. texture.delayLoad();
  16599. return false;
  16600. }
  16601. var internalTexture;
  16602. if (depthStencilTexture) {
  16603. internalTexture = texture.depthStencilTexture;
  16604. }
  16605. else if (texture.isReady()) {
  16606. internalTexture = texture.getInternalTexture();
  16607. }
  16608. else if (texture.isCube) {
  16609. internalTexture = this.emptyCubeTexture;
  16610. }
  16611. else if (texture.is3D) {
  16612. internalTexture = this.emptyTexture3D;
  16613. }
  16614. else {
  16615. internalTexture = this.emptyTexture;
  16616. }
  16617. if (!isPartOfTextureArray) {
  16618. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16619. }
  16620. var needToBind = true;
  16621. if (this._boundTexturesCache[channel] === internalTexture) {
  16622. this._moveBoundTextureOnTop(internalTexture);
  16623. if (!isPartOfTextureArray) {
  16624. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16625. }
  16626. needToBind = false;
  16627. }
  16628. this._activeChannel = channel;
  16629. if (internalTexture && internalTexture.is3D) {
  16630. if (needToBind) {
  16631. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16632. }
  16633. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16634. internalTexture._cachedWrapU = texture.wrapU;
  16635. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16636. }
  16637. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16638. internalTexture._cachedWrapV = texture.wrapV;
  16639. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16640. }
  16641. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16642. internalTexture._cachedWrapR = texture.wrapR;
  16643. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16644. }
  16645. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16646. }
  16647. else if (internalTexture && internalTexture.isCube) {
  16648. if (needToBind) {
  16649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16650. }
  16651. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16652. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16653. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16654. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16655. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16656. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16657. }
  16658. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16659. }
  16660. else {
  16661. if (needToBind) {
  16662. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16663. }
  16664. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16665. internalTexture._cachedWrapU = texture.wrapU;
  16666. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16667. }
  16668. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16669. internalTexture._cachedWrapV = texture.wrapV;
  16670. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16671. }
  16672. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16673. }
  16674. return true;
  16675. };
  16676. /**
  16677. * Sets an array of texture to the webGL context
  16678. * @param channel defines the channel where the texture array must be set
  16679. * @param uniform defines the associated uniform location
  16680. * @param textures defines the array of textures to bind
  16681. */
  16682. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16683. if (channel < 0 || !uniform) {
  16684. return;
  16685. }
  16686. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16687. this._textureUnits = new Int32Array(textures.length);
  16688. }
  16689. for (var i = 0; i < textures.length; i++) {
  16690. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16691. }
  16692. this._gl.uniform1iv(uniform, this._textureUnits);
  16693. for (var index = 0; index < textures.length; index++) {
  16694. this._setTexture(this._textureUnits[index], textures[index], true);
  16695. }
  16696. };
  16697. /** @hidden */
  16698. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16699. var internalTexture = texture.getInternalTexture();
  16700. if (!internalTexture) {
  16701. return;
  16702. }
  16703. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16704. var value = texture.anisotropicFilteringLevel;
  16705. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16706. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16707. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16708. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16709. }
  16710. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16711. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16712. internalTexture._cachedAnisotropicFilteringLevel = value;
  16713. }
  16714. };
  16715. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16716. this._bindTextureDirectly(target, texture, true, true);
  16717. this._gl.texParameterf(target, parameter, value);
  16718. };
  16719. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16720. if (texture) {
  16721. this._bindTextureDirectly(target, texture, true, true);
  16722. }
  16723. this._gl.texParameteri(target, parameter, value);
  16724. };
  16725. /**
  16726. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16727. * @param x defines the x coordinate of the rectangle where pixels must be read
  16728. * @param y defines the y coordinate of the rectangle where pixels must be read
  16729. * @param width defines the width of the rectangle where pixels must be read
  16730. * @param height defines the height of the rectangle where pixels must be read
  16731. * @returns a Uint8Array containing RGBA colors
  16732. */
  16733. Engine.prototype.readPixels = function (x, y, width, height) {
  16734. var data = new Uint8Array(height * width * 4);
  16735. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16736. return data;
  16737. };
  16738. /**
  16739. * Add an externaly attached data from its key.
  16740. * This method call will fail and return false, if such key already exists.
  16741. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16742. * @param key the unique key that identifies the data
  16743. * @param data the data object to associate to the key for this Engine instance
  16744. * @return true if no such key were already present and the data was added successfully, false otherwise
  16745. */
  16746. Engine.prototype.addExternalData = function (key, data) {
  16747. if (!this._externalData) {
  16748. this._externalData = new BABYLON.StringDictionary();
  16749. }
  16750. return this._externalData.add(key, data);
  16751. };
  16752. /**
  16753. * Get an externaly attached data from its key
  16754. * @param key the unique key that identifies the data
  16755. * @return the associated data, if present (can be null), or undefined if not present
  16756. */
  16757. Engine.prototype.getExternalData = function (key) {
  16758. if (!this._externalData) {
  16759. this._externalData = new BABYLON.StringDictionary();
  16760. }
  16761. return this._externalData.get(key);
  16762. };
  16763. /**
  16764. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16765. * @param key the unique key that identifies the data
  16766. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16767. * @return the associated data, can be null if the factory returned null.
  16768. */
  16769. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16770. if (!this._externalData) {
  16771. this._externalData = new BABYLON.StringDictionary();
  16772. }
  16773. return this._externalData.getOrAddWithFactory(key, factory);
  16774. };
  16775. /**
  16776. * Remove an externaly attached data from the Engine instance
  16777. * @param key the unique key that identifies the data
  16778. * @return true if the data was successfully removed, false if it doesn't exist
  16779. */
  16780. Engine.prototype.removeExternalData = function (key) {
  16781. if (!this._externalData) {
  16782. this._externalData = new BABYLON.StringDictionary();
  16783. }
  16784. return this._externalData.remove(key);
  16785. };
  16786. /**
  16787. * Unbind all vertex attributes from the webGL context
  16788. */
  16789. Engine.prototype.unbindAllAttributes = function () {
  16790. if (this._mustWipeVertexAttributes) {
  16791. this._mustWipeVertexAttributes = false;
  16792. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16793. this._gl.disableVertexAttribArray(i);
  16794. this._vertexAttribArraysEnabled[i] = false;
  16795. this._currentBufferPointers[i].active = false;
  16796. }
  16797. return;
  16798. }
  16799. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16800. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16801. continue;
  16802. }
  16803. this._gl.disableVertexAttribArray(i);
  16804. this._vertexAttribArraysEnabled[i] = false;
  16805. this._currentBufferPointers[i].active = false;
  16806. }
  16807. };
  16808. /**
  16809. * 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
  16810. */
  16811. Engine.prototype.releaseEffects = function () {
  16812. for (var name in this._compiledEffects) {
  16813. this._deleteProgram(this._compiledEffects[name]._program);
  16814. }
  16815. this._compiledEffects = {};
  16816. };
  16817. /**
  16818. * Dispose and release all associated resources
  16819. */
  16820. Engine.prototype.dispose = function () {
  16821. this.hideLoadingUI();
  16822. this.stopRenderLoop();
  16823. // Release postProcesses
  16824. while (this.postProcesses.length) {
  16825. this.postProcesses[0].dispose();
  16826. }
  16827. // Empty texture
  16828. if (this._emptyTexture) {
  16829. this._releaseTexture(this._emptyTexture);
  16830. this._emptyTexture = null;
  16831. }
  16832. if (this._emptyCubeTexture) {
  16833. this._releaseTexture(this._emptyCubeTexture);
  16834. this._emptyCubeTexture = null;
  16835. }
  16836. // Rescale PP
  16837. if (this._rescalePostProcess) {
  16838. this._rescalePostProcess.dispose();
  16839. }
  16840. // Release scenes
  16841. while (this.scenes.length) {
  16842. this.scenes[0].dispose();
  16843. }
  16844. // Release audio engine
  16845. if (Engine.audioEngine) {
  16846. Engine.audioEngine.dispose();
  16847. }
  16848. // Release effects
  16849. this.releaseEffects();
  16850. // Unbind
  16851. this.unbindAllAttributes();
  16852. this._boundUniforms = [];
  16853. if (this._dummyFramebuffer) {
  16854. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16855. }
  16856. //WebVR
  16857. this.disableVR();
  16858. // Events
  16859. if (BABYLON.Tools.IsWindowObjectExist()) {
  16860. window.removeEventListener("blur", this._onBlur);
  16861. window.removeEventListener("focus", this._onFocus);
  16862. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16863. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16864. if (this._renderingCanvas) {
  16865. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16866. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16867. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16868. if (!this._doNotHandleContextLost) {
  16869. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16870. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16871. }
  16872. }
  16873. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16874. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16875. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16876. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16877. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16878. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16879. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16880. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16881. if (this._onVrDisplayConnect) {
  16882. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16883. if (this._onVrDisplayDisconnect) {
  16884. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16885. }
  16886. if (this._onVrDisplayPresentChange) {
  16887. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16888. }
  16889. this._onVrDisplayConnect = null;
  16890. this._onVrDisplayDisconnect = null;
  16891. }
  16892. }
  16893. // Remove from Instances
  16894. var index = Engine.Instances.indexOf(this);
  16895. if (index >= 0) {
  16896. Engine.Instances.splice(index, 1);
  16897. }
  16898. this._workingCanvas = null;
  16899. this._workingContext = null;
  16900. this._currentBufferPointers = [];
  16901. this._renderingCanvas = null;
  16902. this._currentProgram = null;
  16903. this._bindedRenderFunction = null;
  16904. this.onResizeObservable.clear();
  16905. this.onCanvasBlurObservable.clear();
  16906. this.onCanvasFocusObservable.clear();
  16907. this.onCanvasPointerOutObservable.clear();
  16908. this.onBeginFrameObservable.clear();
  16909. this.onEndFrameObservable.clear();
  16910. BABYLON.Effect.ResetCache();
  16911. // Abort active requests
  16912. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16913. var request = _a[_i];
  16914. request.abort();
  16915. }
  16916. };
  16917. // Loading screen
  16918. /**
  16919. * Display the loading screen
  16920. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16921. */
  16922. Engine.prototype.displayLoadingUI = function () {
  16923. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16924. return;
  16925. }
  16926. var loadingScreen = this.loadingScreen;
  16927. if (loadingScreen) {
  16928. loadingScreen.displayLoadingUI();
  16929. }
  16930. };
  16931. /**
  16932. * Hide the loading screen
  16933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16934. */
  16935. Engine.prototype.hideLoadingUI = function () {
  16936. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16937. return;
  16938. }
  16939. var loadingScreen = this.loadingScreen;
  16940. if (loadingScreen) {
  16941. loadingScreen.hideLoadingUI();
  16942. }
  16943. };
  16944. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16945. /**
  16946. * Gets the current loading screen object
  16947. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16948. */
  16949. get: function () {
  16950. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16951. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16952. return this._loadingScreen;
  16953. },
  16954. /**
  16955. * Sets the current loading screen object
  16956. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16957. */
  16958. set: function (loadingScreen) {
  16959. this._loadingScreen = loadingScreen;
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16965. /**
  16966. * Sets the current loading screen text
  16967. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16968. */
  16969. set: function (text) {
  16970. this.loadingScreen.loadingUIText = text;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16976. /**
  16977. * Sets the current loading screen background color
  16978. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16979. */
  16980. set: function (color) {
  16981. this.loadingScreen.loadingUIBackgroundColor = color;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. /**
  16987. * Attach a new callback raised when context lost event is fired
  16988. * @param callback defines the callback to call
  16989. */
  16990. Engine.prototype.attachContextLostEvent = function (callback) {
  16991. if (this._renderingCanvas) {
  16992. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16993. }
  16994. };
  16995. /**
  16996. * Attach a new callback raised when context restored event is fired
  16997. * @param callback defines the callback to call
  16998. */
  16999. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17000. if (this._renderingCanvas) {
  17001. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17002. }
  17003. };
  17004. /**
  17005. * Gets the source code of the vertex shader associated with a specific webGL program
  17006. * @param program defines the program to use
  17007. * @returns a string containing the source code of the vertex shader associated with the program
  17008. */
  17009. Engine.prototype.getVertexShaderSource = function (program) {
  17010. var shaders = this._gl.getAttachedShaders(program);
  17011. if (!shaders) {
  17012. return null;
  17013. }
  17014. return this._gl.getShaderSource(shaders[0]);
  17015. };
  17016. /**
  17017. * Gets the source code of the fragment shader associated with a specific webGL program
  17018. * @param program defines the program to use
  17019. * @returns a string containing the source code of the fragment shader associated with the program
  17020. */
  17021. Engine.prototype.getFragmentShaderSource = function (program) {
  17022. var shaders = this._gl.getAttachedShaders(program);
  17023. if (!shaders) {
  17024. return null;
  17025. }
  17026. return this._gl.getShaderSource(shaders[1]);
  17027. };
  17028. /**
  17029. * Get the current error code of the webGL context
  17030. * @returns the error code
  17031. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17032. */
  17033. Engine.prototype.getError = function () {
  17034. return this._gl.getError();
  17035. };
  17036. // FPS
  17037. /**
  17038. * Gets the current framerate
  17039. * @returns a number representing the framerate
  17040. */
  17041. Engine.prototype.getFps = function () {
  17042. return this._fps;
  17043. };
  17044. /**
  17045. * Gets the time spent between current and previous frame
  17046. * @returns a number representing the delta time in ms
  17047. */
  17048. Engine.prototype.getDeltaTime = function () {
  17049. return this._deltaTime;
  17050. };
  17051. Engine.prototype._measureFps = function () {
  17052. this._performanceMonitor.sampleFrame();
  17053. this._fps = this._performanceMonitor.averageFPS;
  17054. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17055. };
  17056. /** @hidden */
  17057. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17058. if (faceIndex === void 0) { faceIndex = -1; }
  17059. if (level === void 0) { level = 0; }
  17060. var gl = this._gl;
  17061. if (!this._dummyFramebuffer) {
  17062. var dummy = gl.createFramebuffer();
  17063. if (!dummy) {
  17064. throw new Error("Unable to create dummy framebuffer");
  17065. }
  17066. this._dummyFramebuffer = dummy;
  17067. }
  17068. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17069. if (faceIndex > -1) {
  17070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17071. }
  17072. else {
  17073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17074. }
  17075. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17076. var buffer;
  17077. switch (readType) {
  17078. case gl.UNSIGNED_BYTE:
  17079. buffer = new Uint8Array(4 * width * height);
  17080. readType = gl.UNSIGNED_BYTE;
  17081. break;
  17082. default:
  17083. buffer = new Float32Array(4 * width * height);
  17084. readType = gl.FLOAT;
  17085. break;
  17086. }
  17087. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17088. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17089. return buffer;
  17090. };
  17091. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17092. if (this._webGLVersion > 1) {
  17093. return this._caps.colorBufferFloat;
  17094. }
  17095. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17096. };
  17097. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17098. if (this._webGLVersion > 1) {
  17099. return this._caps.colorBufferFloat;
  17100. }
  17101. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17102. };
  17103. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17104. Engine.prototype._canRenderToFramebuffer = function (type) {
  17105. var gl = this._gl;
  17106. //clear existing errors
  17107. while (gl.getError() !== gl.NO_ERROR) { }
  17108. var successful = true;
  17109. var texture = gl.createTexture();
  17110. gl.bindTexture(gl.TEXTURE_2D, texture);
  17111. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17114. var fb = gl.createFramebuffer();
  17115. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17117. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17118. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17119. successful = successful && (gl.getError() === gl.NO_ERROR);
  17120. //try render by clearing frame buffer's color buffer
  17121. if (successful) {
  17122. gl.clear(gl.COLOR_BUFFER_BIT);
  17123. successful = successful && (gl.getError() === gl.NO_ERROR);
  17124. }
  17125. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17126. if (successful) {
  17127. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17128. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17129. var readFormat = gl.RGBA;
  17130. var readType = gl.UNSIGNED_BYTE;
  17131. var buffer = new Uint8Array(4);
  17132. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17133. successful = successful && (gl.getError() === gl.NO_ERROR);
  17134. }
  17135. //clean up
  17136. gl.deleteTexture(texture);
  17137. gl.deleteFramebuffer(fb);
  17138. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17139. //clear accumulated errors
  17140. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17141. return successful;
  17142. };
  17143. /** @hidden */
  17144. Engine.prototype._getWebGLTextureType = function (type) {
  17145. if (type === Engine.TEXTURETYPE_FLOAT) {
  17146. return this._gl.FLOAT;
  17147. }
  17148. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17149. // Add Half Float Constant.
  17150. return this._gl.HALF_FLOAT_OES;
  17151. }
  17152. return this._gl.UNSIGNED_BYTE;
  17153. };
  17154. ;
  17155. Engine.prototype._getInternalFormat = function (format) {
  17156. var internalFormat = this._gl.RGBA;
  17157. switch (format) {
  17158. case Engine.TEXTUREFORMAT_ALPHA:
  17159. internalFormat = this._gl.ALPHA;
  17160. break;
  17161. case Engine.TEXTUREFORMAT_LUMINANCE:
  17162. internalFormat = this._gl.LUMINANCE;
  17163. break;
  17164. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17165. internalFormat = this._gl.LUMINANCE_ALPHA;
  17166. break;
  17167. case Engine.TEXTUREFORMAT_RGB:
  17168. internalFormat = this._gl.RGB;
  17169. break;
  17170. case Engine.TEXTUREFORMAT_RGBA:
  17171. internalFormat = this._gl.RGBA;
  17172. break;
  17173. case Engine.TEXTUREFORMAT_R:
  17174. internalFormat = this._gl.RED;
  17175. break;
  17176. case Engine.TEXTUREFORMAT_RG:
  17177. internalFormat = this._gl.RG;
  17178. break;
  17179. }
  17180. return internalFormat;
  17181. };
  17182. /** @hidden */
  17183. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17184. if (this._webGLVersion === 1) {
  17185. if (format !== undefined) {
  17186. switch (format) {
  17187. case Engine.TEXTUREFORMAT_LUMINANCE:
  17188. return this._gl.LUMINANCE;
  17189. case Engine.TEXTUREFORMAT_ALPHA:
  17190. return this._gl.ALPHA;
  17191. }
  17192. }
  17193. return this._gl.RGBA;
  17194. }
  17195. if (type === Engine.TEXTURETYPE_FLOAT) {
  17196. if (format !== undefined) {
  17197. switch (format) {
  17198. case Engine.TEXTUREFORMAT_R:
  17199. return this._gl.R32F;
  17200. case Engine.TEXTUREFORMAT_RG:
  17201. return this._gl.RG32F;
  17202. case Engine.TEXTUREFORMAT_RGB:
  17203. return this._gl.RGB32F;
  17204. }
  17205. }
  17206. return this._gl.RGBA32F;
  17207. }
  17208. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17209. if (format) {
  17210. switch (format) {
  17211. case Engine.TEXTUREFORMAT_R:
  17212. return this._gl.R16F;
  17213. case Engine.TEXTUREFORMAT_RG:
  17214. return this._gl.RG16F;
  17215. case Engine.TEXTUREFORMAT_RGB:
  17216. return this._gl.RGB16F;
  17217. }
  17218. }
  17219. return this._gl.RGBA16F;
  17220. }
  17221. if (format !== undefined) {
  17222. switch (format) {
  17223. case Engine.TEXTUREFORMAT_LUMINANCE:
  17224. return this._gl.LUMINANCE;
  17225. case Engine.TEXTUREFORMAT_RGB:
  17226. return this._gl.RGB;
  17227. case Engine.TEXTUREFORMAT_R:
  17228. return this._gl.R8;
  17229. case Engine.TEXTUREFORMAT_RG:
  17230. return this._gl.RG8;
  17231. case Engine.TEXTUREFORMAT_ALPHA:
  17232. return this._gl.ALPHA;
  17233. }
  17234. }
  17235. return this._gl.RGBA;
  17236. };
  17237. ;
  17238. /** @hidden */
  17239. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17240. if (type === Engine.TEXTURETYPE_FLOAT) {
  17241. return this._gl.RGBA32F;
  17242. }
  17243. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17244. return this._gl.RGBA16F;
  17245. }
  17246. return this._gl.RGBA8;
  17247. };
  17248. ;
  17249. /**
  17250. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17251. * @return the new query
  17252. */
  17253. Engine.prototype.createQuery = function () {
  17254. return this._gl.createQuery();
  17255. };
  17256. /**
  17257. * Delete and release a webGL query
  17258. * @param query defines the query to delete
  17259. * @return the current engine
  17260. */
  17261. Engine.prototype.deleteQuery = function (query) {
  17262. this._gl.deleteQuery(query);
  17263. return this;
  17264. };
  17265. /**
  17266. * Check if a given query has resolved and got its value
  17267. * @param query defines the query to check
  17268. * @returns true if the query got its value
  17269. */
  17270. Engine.prototype.isQueryResultAvailable = function (query) {
  17271. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17272. };
  17273. /**
  17274. * Gets the value of a given query
  17275. * @param query defines the query to check
  17276. * @returns the value of the query
  17277. */
  17278. Engine.prototype.getQueryResult = function (query) {
  17279. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17280. };
  17281. /**
  17282. * Initiates an occlusion query
  17283. * @param algorithmType defines the algorithm to use
  17284. * @param query defines the query to use
  17285. * @returns the current engine
  17286. * @see http://doc.babylonjs.com/features/occlusionquery
  17287. */
  17288. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17289. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17290. this._gl.beginQuery(glAlgorithm, query);
  17291. return this;
  17292. };
  17293. /**
  17294. * Ends an occlusion query
  17295. * @see http://doc.babylonjs.com/features/occlusionquery
  17296. * @param algorithmType defines the algorithm to use
  17297. * @returns the current engine
  17298. */
  17299. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17300. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17301. this._gl.endQuery(glAlgorithm);
  17302. return this;
  17303. };
  17304. /* Time queries */
  17305. Engine.prototype._createTimeQuery = function () {
  17306. var timerQuery = this._caps.timerQuery;
  17307. if (timerQuery.createQueryEXT) {
  17308. return timerQuery.createQueryEXT();
  17309. }
  17310. return this.createQuery();
  17311. };
  17312. Engine.prototype._deleteTimeQuery = function (query) {
  17313. var timerQuery = this._caps.timerQuery;
  17314. if (timerQuery.deleteQueryEXT) {
  17315. timerQuery.deleteQueryEXT(query);
  17316. return;
  17317. }
  17318. this.deleteQuery(query);
  17319. };
  17320. Engine.prototype._getTimeQueryResult = function (query) {
  17321. var timerQuery = this._caps.timerQuery;
  17322. if (timerQuery.getQueryObjectEXT) {
  17323. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17324. }
  17325. return this.getQueryResult(query);
  17326. };
  17327. Engine.prototype._getTimeQueryAvailability = function (query) {
  17328. var timerQuery = this._caps.timerQuery;
  17329. if (timerQuery.getQueryObjectEXT) {
  17330. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17331. }
  17332. return this.isQueryResultAvailable(query);
  17333. };
  17334. /**
  17335. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17336. * Please note that only one query can be issued at a time
  17337. * @returns a time token used to track the time span
  17338. */
  17339. Engine.prototype.startTimeQuery = function () {
  17340. var timerQuery = this._caps.timerQuery;
  17341. if (!timerQuery) {
  17342. return null;
  17343. }
  17344. var token = new BABYLON._TimeToken();
  17345. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17346. if (this._caps.canUseTimestampForTimerQuery) {
  17347. token._startTimeQuery = this._createTimeQuery();
  17348. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17349. }
  17350. else {
  17351. if (this._currentNonTimestampToken) {
  17352. return this._currentNonTimestampToken;
  17353. }
  17354. token._timeElapsedQuery = this._createTimeQuery();
  17355. if (timerQuery.beginQueryEXT) {
  17356. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17357. }
  17358. else {
  17359. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17360. }
  17361. this._currentNonTimestampToken = token;
  17362. }
  17363. return token;
  17364. };
  17365. /**
  17366. * Ends a time query
  17367. * @param token defines the token used to measure the time span
  17368. * @returns the time spent (in ns)
  17369. */
  17370. Engine.prototype.endTimeQuery = function (token) {
  17371. var timerQuery = this._caps.timerQuery;
  17372. if (!timerQuery || !token) {
  17373. return -1;
  17374. }
  17375. if (this._caps.canUseTimestampForTimerQuery) {
  17376. if (!token._startTimeQuery) {
  17377. return -1;
  17378. }
  17379. if (!token._endTimeQuery) {
  17380. token._endTimeQuery = this._createTimeQuery();
  17381. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17382. }
  17383. }
  17384. else if (!token._timeElapsedQueryEnded) {
  17385. if (!token._timeElapsedQuery) {
  17386. return -1;
  17387. }
  17388. if (timerQuery.endQueryEXT) {
  17389. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17390. }
  17391. else {
  17392. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17393. }
  17394. token._timeElapsedQueryEnded = true;
  17395. }
  17396. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17397. var available = false;
  17398. if (token._endTimeQuery) {
  17399. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17400. }
  17401. else if (token._timeElapsedQuery) {
  17402. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17403. }
  17404. if (available && !disjoint) {
  17405. var result = 0;
  17406. if (this._caps.canUseTimestampForTimerQuery) {
  17407. if (!token._startTimeQuery || !token._endTimeQuery) {
  17408. return -1;
  17409. }
  17410. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17411. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17412. result = timeEnd - timeStart;
  17413. this._deleteTimeQuery(token._startTimeQuery);
  17414. this._deleteTimeQuery(token._endTimeQuery);
  17415. token._startTimeQuery = null;
  17416. token._endTimeQuery = null;
  17417. }
  17418. else {
  17419. if (!token._timeElapsedQuery) {
  17420. return -1;
  17421. }
  17422. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17423. this._deleteTimeQuery(token._timeElapsedQuery);
  17424. token._timeElapsedQuery = null;
  17425. token._timeElapsedQueryEnded = false;
  17426. this._currentNonTimestampToken = null;
  17427. }
  17428. return result;
  17429. }
  17430. return -1;
  17431. };
  17432. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17433. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17434. };
  17435. // Transform feedback
  17436. /**
  17437. * Creates a webGL transform feedback object
  17438. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17439. * @returns the webGL transform feedback object
  17440. */
  17441. Engine.prototype.createTransformFeedback = function () {
  17442. return this._gl.createTransformFeedback();
  17443. };
  17444. /**
  17445. * Delete a webGL transform feedback object
  17446. * @param value defines the webGL transform feedback object to delete
  17447. */
  17448. Engine.prototype.deleteTransformFeedback = function (value) {
  17449. this._gl.deleteTransformFeedback(value);
  17450. };
  17451. /**
  17452. * Bind a webGL transform feedback object to the webgl context
  17453. * @param value defines the webGL transform feedback object to bind
  17454. */
  17455. Engine.prototype.bindTransformFeedback = function (value) {
  17456. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17457. };
  17458. /**
  17459. * Begins a transform feedback operation
  17460. * @param usePoints defines if points or triangles must be used
  17461. */
  17462. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17463. if (usePoints === void 0) { usePoints = true; }
  17464. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17465. };
  17466. /**
  17467. * Ends a transform feedback operation
  17468. */
  17469. Engine.prototype.endTransformFeedback = function () {
  17470. this._gl.endTransformFeedback();
  17471. };
  17472. /**
  17473. * Specify the varyings to use with transform feedback
  17474. * @param program defines the associated webGL program
  17475. * @param value defines the list of strings representing the varying names
  17476. */
  17477. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17478. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17479. };
  17480. /**
  17481. * Bind a webGL buffer for a transform feedback operation
  17482. * @param value defines the webGL buffer to bind
  17483. */
  17484. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17485. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17486. };
  17487. /** @hidden */
  17488. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17489. var _this = this;
  17490. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17491. this._activeRequests.push(request);
  17492. request.onCompleteObservable.add(function (request) {
  17493. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17494. });
  17495. return request;
  17496. };
  17497. /** @hidden */
  17498. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17499. var _this = this;
  17500. return new Promise(function (resolve, reject) {
  17501. _this._loadFile(url, function (data) {
  17502. resolve(data);
  17503. }, undefined, database, useArrayBuffer, function (request, exception) {
  17504. reject(exception);
  17505. });
  17506. });
  17507. };
  17508. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17509. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17510. var onload = function (data) {
  17511. loadedFiles[index] = data;
  17512. loadedFiles._internalCount++;
  17513. if (loadedFiles._internalCount === 6) {
  17514. onfinish(loadedFiles);
  17515. }
  17516. };
  17517. var onerror = function (request, exception) {
  17518. if (onErrorCallBack && request) {
  17519. onErrorCallBack(request.status + " " + request.statusText, exception);
  17520. }
  17521. };
  17522. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17523. };
  17524. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17525. if (onError === void 0) { onError = null; }
  17526. var loadedFiles = [];
  17527. loadedFiles._internalCount = 0;
  17528. for (var index = 0; index < 6; index++) {
  17529. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17530. }
  17531. };
  17532. // Statics
  17533. /**
  17534. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17535. * @returns true if the engine can be created
  17536. * @ignorenaming
  17537. */
  17538. Engine.isSupported = function () {
  17539. try {
  17540. var tempcanvas = document.createElement("canvas");
  17541. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17542. return gl != null && !!window.WebGLRenderingContext;
  17543. }
  17544. catch (e) {
  17545. return false;
  17546. }
  17547. };
  17548. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17549. Engine.ExceptionList = [
  17550. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17551. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17552. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17553. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17554. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17555. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17556. ];
  17557. /** Gets the list of created engines */
  17558. Engine.Instances = new Array();
  17559. // Const statics
  17560. Engine._ALPHA_DISABLE = 0;
  17561. Engine._ALPHA_ADD = 1;
  17562. Engine._ALPHA_COMBINE = 2;
  17563. Engine._ALPHA_SUBTRACT = 3;
  17564. Engine._ALPHA_MULTIPLY = 4;
  17565. Engine._ALPHA_MAXIMIZED = 5;
  17566. Engine._ALPHA_ONEONE = 6;
  17567. Engine._ALPHA_PREMULTIPLIED = 7;
  17568. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17569. Engine._ALPHA_INTERPOLATE = 9;
  17570. Engine._ALPHA_SCREENMODE = 10;
  17571. Engine._DELAYLOADSTATE_NONE = 0;
  17572. Engine._DELAYLOADSTATE_LOADED = 1;
  17573. Engine._DELAYLOADSTATE_LOADING = 2;
  17574. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17575. Engine._TEXTUREFORMAT_ALPHA = 0;
  17576. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17577. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17578. Engine._TEXTUREFORMAT_RGB = 4;
  17579. Engine._TEXTUREFORMAT_RGBA = 5;
  17580. Engine._TEXTUREFORMAT_R = 6;
  17581. Engine._TEXTUREFORMAT_RG = 7;
  17582. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17583. Engine._TEXTURETYPE_FLOAT = 1;
  17584. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17585. // Depht or Stencil test Constants.
  17586. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17587. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17588. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17589. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17590. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17591. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17592. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17593. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17594. // Stencil Actions Constants.
  17595. Engine._KEEP = 0x1E00;
  17596. Engine._REPLACE = 0x1E01;
  17597. Engine._INCR = 0x1E02;
  17598. Engine._DECR = 0x1E03;
  17599. Engine._INVERT = 0x150A;
  17600. Engine._INCR_WRAP = 0x8507;
  17601. Engine._DECR_WRAP = 0x8508;
  17602. // Texture rescaling mode
  17603. Engine._SCALEMODE_FLOOR = 1;
  17604. Engine._SCALEMODE_NEAREST = 2;
  17605. Engine._SCALEMODE_CEILING = 3;
  17606. // Updatable statics so stick with vars here
  17607. /**
  17608. * Gets or sets the epsilon value used by collision engine
  17609. */
  17610. Engine.CollisionsEpsilon = 0.001;
  17611. /**
  17612. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17613. */
  17614. Engine.CodeRepository = "src/";
  17615. /**
  17616. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17617. */
  17618. Engine.ShadersRepository = "src/Shaders/";
  17619. return Engine;
  17620. }());
  17621. BABYLON.Engine = Engine;
  17622. })(BABYLON || (BABYLON = {}));
  17623. //# sourceMappingURL=babylon.engine.js.map
  17624. var BABYLON;
  17625. (function (BABYLON) {
  17626. /**
  17627. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17628. */
  17629. var Node = /** @class */ (function () {
  17630. /**
  17631. * Creates a new Node
  17632. * @param {string} name - the name and id to be given to this node
  17633. * @param {BABYLON.Scene} the scene this node will be added to
  17634. */
  17635. function Node(name, scene) {
  17636. if (scene === void 0) { scene = null; }
  17637. /**
  17638. * Gets or sets a string used to store user defined state for the node
  17639. */
  17640. this.state = "";
  17641. /**
  17642. * Gets or sets an object used to store user defined information for the node
  17643. */
  17644. this.metadata = null;
  17645. /**
  17646. * Gets or sets a boolean used to define if the node must be serialized
  17647. */
  17648. this.doNotSerialize = false;
  17649. /** @hidden */
  17650. this._isDisposed = false;
  17651. /**
  17652. * Gets a list of Animations associated with the node
  17653. */
  17654. this.animations = new Array();
  17655. this._ranges = {};
  17656. this._isEnabled = true;
  17657. this._isReady = true;
  17658. /** @hidden */
  17659. this._currentRenderId = -1;
  17660. this._parentRenderId = -1;
  17661. this._childRenderId = -1;
  17662. this._animationPropertiesOverride = null;
  17663. /**
  17664. * An event triggered when the mesh is disposed
  17665. */
  17666. this.onDisposeObservable = new BABYLON.Observable();
  17667. // Behaviors
  17668. this._behaviors = new Array();
  17669. this.name = name;
  17670. this.id = name;
  17671. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17672. this.uniqueId = this._scene.getUniqueId();
  17673. this._initCache();
  17674. }
  17675. /**
  17676. * Gets a boolean indicating if the node has been disposed
  17677. * @returns true if the node was disposed
  17678. */
  17679. Node.prototype.isDisposed = function () {
  17680. return this._isDisposed;
  17681. };
  17682. Object.defineProperty(Node.prototype, "parent", {
  17683. get: function () {
  17684. return this._parentNode;
  17685. },
  17686. /**
  17687. * Gets or sets the parent of the node
  17688. */
  17689. set: function (parent) {
  17690. if (this._parentNode === parent) {
  17691. return;
  17692. }
  17693. // Remove self from list of children of parent
  17694. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17695. var index = this._parentNode._children.indexOf(this);
  17696. if (index !== -1) {
  17697. this._parentNode._children.splice(index, 1);
  17698. }
  17699. }
  17700. // Store new parent
  17701. this._parentNode = parent;
  17702. // Add as child to new parent
  17703. if (this._parentNode) {
  17704. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17705. this._parentNode._children = new Array();
  17706. }
  17707. this._parentNode._children.push(this);
  17708. }
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17714. /**
  17715. * Gets or sets the animation properties override
  17716. */
  17717. get: function () {
  17718. if (!this._animationPropertiesOverride) {
  17719. return this._scene.animationPropertiesOverride;
  17720. }
  17721. return this._animationPropertiesOverride;
  17722. },
  17723. set: function (value) {
  17724. this._animationPropertiesOverride = value;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. /**
  17730. * Gets a string idenfifying the name of the class
  17731. * @returns "Node" string
  17732. */
  17733. Node.prototype.getClassName = function () {
  17734. return "Node";
  17735. };
  17736. Object.defineProperty(Node.prototype, "onDispose", {
  17737. /**
  17738. * Sets a callback that will be raised when the node will be disposed
  17739. */
  17740. set: function (callback) {
  17741. if (this._onDisposeObserver) {
  17742. this.onDisposeObservable.remove(this._onDisposeObserver);
  17743. }
  17744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. /**
  17750. * Gets the scene of the node
  17751. * @returns a {BABYLON.Scene}
  17752. */
  17753. Node.prototype.getScene = function () {
  17754. return this._scene;
  17755. };
  17756. /**
  17757. * Gets the engine of the node
  17758. * @returns a {BABYLON.Engine}
  17759. */
  17760. Node.prototype.getEngine = function () {
  17761. return this._scene.getEngine();
  17762. };
  17763. /**
  17764. * Attach a behavior to the node
  17765. * @see http://doc.babylonjs.com/features/behaviour
  17766. * @param behavior defines the behavior to attach
  17767. * @returns the current Node
  17768. */
  17769. Node.prototype.addBehavior = function (behavior) {
  17770. var _this = this;
  17771. var index = this._behaviors.indexOf(behavior);
  17772. if (index !== -1) {
  17773. return this;
  17774. }
  17775. behavior.init();
  17776. if (this._scene.isLoading) {
  17777. // We defer the attach when the scene will be loaded
  17778. this._scene.onDataLoadedObservable.addOnce(function () {
  17779. behavior.attach(_this);
  17780. });
  17781. }
  17782. else {
  17783. behavior.attach(this);
  17784. }
  17785. this._behaviors.push(behavior);
  17786. return this;
  17787. };
  17788. /**
  17789. * Remove an attached behavior
  17790. * @see http://doc.babylonjs.com/features/behaviour
  17791. * @param behavior defines the behavior to attach
  17792. * @returns the current Node
  17793. */
  17794. Node.prototype.removeBehavior = function (behavior) {
  17795. var index = this._behaviors.indexOf(behavior);
  17796. if (index === -1) {
  17797. return this;
  17798. }
  17799. this._behaviors[index].detach();
  17800. this._behaviors.splice(index, 1);
  17801. return this;
  17802. };
  17803. Object.defineProperty(Node.prototype, "behaviors", {
  17804. /**
  17805. * Gets the list of attached behaviors
  17806. * @see http://doc.babylonjs.com/features/behaviour
  17807. */
  17808. get: function () {
  17809. return this._behaviors;
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. /**
  17815. * Gets an attached behavior by name
  17816. * @param name defines the name of the behavior to look for
  17817. * @see http://doc.babylonjs.com/features/behaviour
  17818. * @returns null if behavior was not found else the requested behavior
  17819. */
  17820. Node.prototype.getBehaviorByName = function (name) {
  17821. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17822. var behavior = _a[_i];
  17823. if (behavior.name === name) {
  17824. return behavior;
  17825. }
  17826. }
  17827. return null;
  17828. };
  17829. /**
  17830. * Returns the world matrix of the node
  17831. * @returns a matrix containing the node's world matrix
  17832. */
  17833. Node.prototype.getWorldMatrix = function () {
  17834. return BABYLON.Matrix.Identity();
  17835. };
  17836. /** @hidden */
  17837. Node.prototype._getWorldMatrixDeterminant = function () {
  17838. return 1;
  17839. };
  17840. // override it in derived class if you add new variables to the cache
  17841. // and call the parent class method
  17842. /** @hidden */
  17843. Node.prototype._initCache = function () {
  17844. this._cache = {};
  17845. this._cache.parent = undefined;
  17846. };
  17847. /** @hidden */
  17848. Node.prototype.updateCache = function (force) {
  17849. if (!force && this.isSynchronized())
  17850. return;
  17851. this._cache.parent = this.parent;
  17852. this._updateCache();
  17853. };
  17854. // override it in derived class if you add new variables to the cache
  17855. // and call the parent class method if !ignoreParentClass
  17856. /** @hidden */
  17857. Node.prototype._updateCache = function (ignoreParentClass) {
  17858. };
  17859. // override it in derived class if you add new variables to the cache
  17860. /** @hidden */
  17861. Node.prototype._isSynchronized = function () {
  17862. return true;
  17863. };
  17864. /** @hidden */
  17865. Node.prototype._markSyncedWithParent = function () {
  17866. if (this.parent) {
  17867. this._parentRenderId = this.parent._childRenderId;
  17868. }
  17869. };
  17870. /** @hidden */
  17871. Node.prototype.isSynchronizedWithParent = function () {
  17872. if (!this.parent) {
  17873. return true;
  17874. }
  17875. if (this._parentRenderId !== this.parent._childRenderId) {
  17876. return false;
  17877. }
  17878. return this.parent.isSynchronized();
  17879. };
  17880. /** @hidden */
  17881. Node.prototype.isSynchronized = function (updateCache) {
  17882. var check = this.hasNewParent();
  17883. check = check || !this.isSynchronizedWithParent();
  17884. check = check || !this._isSynchronized();
  17885. if (updateCache)
  17886. this.updateCache(true);
  17887. return !check;
  17888. };
  17889. /** @hidden */
  17890. Node.prototype.hasNewParent = function (update) {
  17891. if (this._cache.parent === this.parent)
  17892. return false;
  17893. if (update)
  17894. this._cache.parent = this.parent;
  17895. return true;
  17896. };
  17897. /**
  17898. * Is this node ready to be used/rendered
  17899. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17900. * @return true if the node is ready
  17901. */
  17902. Node.prototype.isReady = function (completeCheck) {
  17903. if (completeCheck === void 0) { completeCheck = false; }
  17904. return this._isReady;
  17905. };
  17906. /**
  17907. * Is this node enabled?
  17908. * 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
  17909. * @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
  17910. * @return whether this node (and its parent) is enabled
  17911. */
  17912. Node.prototype.isEnabled = function (checkAncestors) {
  17913. if (checkAncestors === void 0) { checkAncestors = true; }
  17914. if (checkAncestors === false) {
  17915. return this._isEnabled;
  17916. }
  17917. if (this._isEnabled === false) {
  17918. return false;
  17919. }
  17920. if (this.parent !== undefined && this.parent !== null) {
  17921. return this.parent.isEnabled(checkAncestors);
  17922. }
  17923. return true;
  17924. };
  17925. /**
  17926. * Set the enabled state of this node
  17927. * @param value defines the new enabled state
  17928. */
  17929. Node.prototype.setEnabled = function (value) {
  17930. this._isEnabled = value;
  17931. };
  17932. /**
  17933. * Is this node a descendant of the given node?
  17934. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17935. * @param ancestor defines the parent node to inspect
  17936. * @returns a boolean indicating if this node is a descendant of the given node
  17937. */
  17938. Node.prototype.isDescendantOf = function (ancestor) {
  17939. if (this.parent) {
  17940. if (this.parent === ancestor) {
  17941. return true;
  17942. }
  17943. return this.parent.isDescendantOf(ancestor);
  17944. }
  17945. return false;
  17946. };
  17947. /** @hidden */
  17948. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17949. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17950. if (!this._children) {
  17951. return;
  17952. }
  17953. for (var index = 0; index < this._children.length; index++) {
  17954. var item = this._children[index];
  17955. if (!predicate || predicate(item)) {
  17956. results.push(item);
  17957. }
  17958. if (!directDescendantsOnly) {
  17959. item._getDescendants(results, false, predicate);
  17960. }
  17961. }
  17962. };
  17963. /**
  17964. * Will return all nodes that have this node as ascendant
  17965. * @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
  17966. * @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
  17967. * @return all children nodes of all types
  17968. */
  17969. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17970. var results = new Array();
  17971. this._getDescendants(results, directDescendantsOnly, predicate);
  17972. return results;
  17973. };
  17974. /**
  17975. * Get all child-meshes of this node
  17976. * @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
  17977. * @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
  17978. * @returns an array of {BABYLON.AbstractMesh}
  17979. */
  17980. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17981. var results = [];
  17982. this._getDescendants(results, directDescendantsOnly, function (node) {
  17983. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17984. });
  17985. return results;
  17986. };
  17987. /**
  17988. * Get all child-transformNodes of this node
  17989. * @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
  17990. * @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
  17991. * @returns an array of {BABYLON.TransformNode}
  17992. */
  17993. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17994. var results = [];
  17995. this._getDescendants(results, directDescendantsOnly, function (node) {
  17996. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17997. });
  17998. return results;
  17999. };
  18000. /**
  18001. * Get all direct children of this node
  18002. * @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
  18003. * @returns an array of {BABYLON.Node}
  18004. */
  18005. Node.prototype.getChildren = function (predicate) {
  18006. return this.getDescendants(true, predicate);
  18007. };
  18008. /** @hidden */
  18009. Node.prototype._setReady = function (state) {
  18010. if (state === this._isReady) {
  18011. return;
  18012. }
  18013. if (!state) {
  18014. this._isReady = false;
  18015. return;
  18016. }
  18017. if (this.onReady) {
  18018. this.onReady(this);
  18019. }
  18020. this._isReady = true;
  18021. };
  18022. /**
  18023. * Get an animation by name
  18024. * @param name defines the name of the animation to look for
  18025. * @returns null if not found else the requested animation
  18026. */
  18027. Node.prototype.getAnimationByName = function (name) {
  18028. for (var i = 0; i < this.animations.length; i++) {
  18029. var animation = this.animations[i];
  18030. if (animation.name === name) {
  18031. return animation;
  18032. }
  18033. }
  18034. return null;
  18035. };
  18036. /**
  18037. * Creates an animation range for this node
  18038. * @param name defines the name of the range
  18039. * @param from defines the starting key
  18040. * @param to defines the end key
  18041. */
  18042. Node.prototype.createAnimationRange = function (name, from, to) {
  18043. // check name not already in use
  18044. if (!this._ranges[name]) {
  18045. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18046. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18047. if (this.animations[i]) {
  18048. this.animations[i].createRange(name, from, to);
  18049. }
  18050. }
  18051. }
  18052. };
  18053. /**
  18054. * Delete a specific animation range
  18055. * @param name defines the name of the range to delete
  18056. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18057. */
  18058. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18059. if (deleteFrames === void 0) { deleteFrames = true; }
  18060. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18061. if (this.animations[i]) {
  18062. this.animations[i].deleteRange(name, deleteFrames);
  18063. }
  18064. }
  18065. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18066. };
  18067. /**
  18068. * Get an animation range by name
  18069. * @param name defines the name of the animation range to look for
  18070. * @returns null if not found else the requested animation range
  18071. */
  18072. Node.prototype.getAnimationRange = function (name) {
  18073. return this._ranges[name];
  18074. };
  18075. /**
  18076. * Will start the animation sequence
  18077. * @param name defines the range frames for animation sequence
  18078. * @param loop defines if the animation should loop (false by default)
  18079. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18080. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18081. * @returns the object created for this animation. If range does not exist, it will return null
  18082. */
  18083. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18084. var range = this.getAnimationRange(name);
  18085. if (!range) {
  18086. return null;
  18087. }
  18088. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18089. };
  18090. /**
  18091. * Serialize animation ranges into a JSON compatible object
  18092. * @returns serialization object
  18093. */
  18094. Node.prototype.serializeAnimationRanges = function () {
  18095. var serializationRanges = [];
  18096. for (var name in this._ranges) {
  18097. var localRange = this._ranges[name];
  18098. if (!localRange) {
  18099. continue;
  18100. }
  18101. var range = {};
  18102. range.name = name;
  18103. range.from = localRange.from;
  18104. range.to = localRange.to;
  18105. serializationRanges.push(range);
  18106. }
  18107. return serializationRanges;
  18108. };
  18109. /**
  18110. * Computes the world matrix of the node
  18111. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18112. * @returns the world matrix
  18113. */
  18114. Node.prototype.computeWorldMatrix = function (force) {
  18115. return BABYLON.Matrix.Identity();
  18116. };
  18117. /**
  18118. * Releases resources associated with this node.
  18119. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18120. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18121. */
  18122. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18123. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18124. if (!doNotRecurse) {
  18125. var nodes = this.getDescendants(true);
  18126. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18127. var node = nodes_1[_i];
  18128. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18129. }
  18130. }
  18131. else {
  18132. var transformNodes = this.getChildTransformNodes(true);
  18133. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18134. var transformNode = transformNodes_1[_a];
  18135. transformNode.parent = null;
  18136. transformNode.computeWorldMatrix(true);
  18137. }
  18138. }
  18139. this.parent = null;
  18140. // Callback
  18141. this.onDisposeObservable.notifyObservers(this);
  18142. this.onDisposeObservable.clear();
  18143. // Behaviors
  18144. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18145. var behavior = _c[_b];
  18146. behavior.detach();
  18147. }
  18148. this._behaviors = [];
  18149. this._isDisposed = true;
  18150. };
  18151. /**
  18152. * Parse animation range data from a serialization object and store them into a given node
  18153. * @param node defines where to store the animation ranges
  18154. * @param parsedNode defines the serialization object to read data from
  18155. * @param scene defines the hosting scene
  18156. */
  18157. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18158. if (parsedNode.ranges) {
  18159. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18160. var data = parsedNode.ranges[index];
  18161. node.createAnimationRange(data.name, data.from, data.to);
  18162. }
  18163. }
  18164. };
  18165. __decorate([
  18166. BABYLON.serialize()
  18167. ], Node.prototype, "name", void 0);
  18168. __decorate([
  18169. BABYLON.serialize()
  18170. ], Node.prototype, "id", void 0);
  18171. __decorate([
  18172. BABYLON.serialize()
  18173. ], Node.prototype, "uniqueId", void 0);
  18174. __decorate([
  18175. BABYLON.serialize()
  18176. ], Node.prototype, "state", void 0);
  18177. __decorate([
  18178. BABYLON.serialize()
  18179. ], Node.prototype, "metadata", void 0);
  18180. return Node;
  18181. }());
  18182. BABYLON.Node = Node;
  18183. })(BABYLON || (BABYLON = {}));
  18184. //# sourceMappingURL=babylon.node.js.map
  18185. var BABYLON;
  18186. (function (BABYLON) {
  18187. var BoundingSphere = /** @class */ (function () {
  18188. /**
  18189. * Creates a new bounding sphere
  18190. * @param min defines the minimum vector (in local space)
  18191. * @param max defines the maximum vector (in local space)
  18192. */
  18193. function BoundingSphere(min, max) {
  18194. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18195. this.reConstruct(min, max);
  18196. }
  18197. /**
  18198. * Recreates the entire bounding sphere from scratch
  18199. * @param min defines the new minimum vector (in local space)
  18200. * @param max defines the new maximum vector (in local space)
  18201. */
  18202. BoundingSphere.prototype.reConstruct = function (min, max) {
  18203. this.minimum = min.clone();
  18204. this.maximum = max.clone();
  18205. var distance = BABYLON.Vector3.Distance(min, max);
  18206. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18207. this.radius = distance * 0.5;
  18208. this.centerWorld = BABYLON.Vector3.Zero();
  18209. this._update(BABYLON.Matrix.Identity());
  18210. };
  18211. // Methods
  18212. BoundingSphere.prototype._update = function (world) {
  18213. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18214. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18215. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18216. };
  18217. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18218. for (var i = 0; i < 6; i++) {
  18219. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18220. return false;
  18221. }
  18222. return true;
  18223. };
  18224. BoundingSphere.prototype.intersectsPoint = function (point) {
  18225. var x = this.centerWorld.x - point.x;
  18226. var y = this.centerWorld.y - point.y;
  18227. var z = this.centerWorld.z - point.z;
  18228. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18229. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18230. return false;
  18231. return true;
  18232. };
  18233. // Statics
  18234. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18235. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18236. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18237. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18238. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18239. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18240. return false;
  18241. return true;
  18242. };
  18243. return BoundingSphere;
  18244. }());
  18245. BABYLON.BoundingSphere = BoundingSphere;
  18246. })(BABYLON || (BABYLON = {}));
  18247. //# sourceMappingURL=babylon.boundingSphere.js.map
  18248. var BABYLON;
  18249. (function (BABYLON) {
  18250. var BoundingBox = /** @class */ (function () {
  18251. /**
  18252. * Creates a new bounding box
  18253. * @param min defines the minimum vector (in local space)
  18254. * @param max defines the maximum vector (in local space)
  18255. */
  18256. function BoundingBox(min, max) {
  18257. this.vectorsWorld = new Array();
  18258. this.reConstruct(min, max);
  18259. }
  18260. // Methods
  18261. /**
  18262. * Recreates the entire bounding box from scratch
  18263. * @param min defines the new minimum vector (in local space)
  18264. * @param max defines the new maximum vector (in local space)
  18265. */
  18266. BoundingBox.prototype.reConstruct = function (min, max) {
  18267. this.minimum = min.clone();
  18268. this.maximum = max.clone();
  18269. // Bounding vectors
  18270. this.vectors = new Array();
  18271. this.vectors.push(this.minimum.clone());
  18272. this.vectors.push(this.maximum.clone());
  18273. this.vectors.push(this.minimum.clone());
  18274. this.vectors[2].x = this.maximum.x;
  18275. this.vectors.push(this.minimum.clone());
  18276. this.vectors[3].y = this.maximum.y;
  18277. this.vectors.push(this.minimum.clone());
  18278. this.vectors[4].z = this.maximum.z;
  18279. this.vectors.push(this.maximum.clone());
  18280. this.vectors[5].z = this.minimum.z;
  18281. this.vectors.push(this.maximum.clone());
  18282. this.vectors[6].x = this.minimum.x;
  18283. this.vectors.push(this.maximum.clone());
  18284. this.vectors[7].y = this.minimum.y;
  18285. // OBB
  18286. this.center = this.maximum.add(this.minimum).scale(0.5);
  18287. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18288. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18289. // World
  18290. for (var index = 0; index < this.vectors.length; index++) {
  18291. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18292. }
  18293. this.minimumWorld = BABYLON.Vector3.Zero();
  18294. this.maximumWorld = BABYLON.Vector3.Zero();
  18295. this.centerWorld = BABYLON.Vector3.Zero();
  18296. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18297. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18298. };
  18299. BoundingBox.prototype.getWorldMatrix = function () {
  18300. return this._worldMatrix;
  18301. };
  18302. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18303. this._worldMatrix.copyFrom(matrix);
  18304. return this;
  18305. };
  18306. BoundingBox.prototype._update = function (world) {
  18307. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18308. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18309. for (var index = 0; index < this.vectors.length; index++) {
  18310. var v = this.vectorsWorld[index];
  18311. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18312. if (v.x < this.minimumWorld.x)
  18313. this.minimumWorld.x = v.x;
  18314. if (v.y < this.minimumWorld.y)
  18315. this.minimumWorld.y = v.y;
  18316. if (v.z < this.minimumWorld.z)
  18317. this.minimumWorld.z = v.z;
  18318. if (v.x > this.maximumWorld.x)
  18319. this.maximumWorld.x = v.x;
  18320. if (v.y > this.maximumWorld.y)
  18321. this.maximumWorld.y = v.y;
  18322. if (v.z > this.maximumWorld.z)
  18323. this.maximumWorld.z = v.z;
  18324. }
  18325. // Extend
  18326. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18327. this.extendSizeWorld.scaleInPlace(0.5);
  18328. // OBB
  18329. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18330. this.centerWorld.scaleInPlace(0.5);
  18331. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18332. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18333. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18334. this._worldMatrix = world;
  18335. };
  18336. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18337. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18338. };
  18339. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18340. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18341. };
  18342. BoundingBox.prototype.intersectsPoint = function (point) {
  18343. var delta = -BABYLON.Epsilon;
  18344. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18345. return false;
  18346. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18347. return false;
  18348. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18349. return false;
  18350. return true;
  18351. };
  18352. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18353. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18354. };
  18355. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18356. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18357. return false;
  18358. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18359. return false;
  18360. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18361. return false;
  18362. return true;
  18363. };
  18364. // Statics
  18365. BoundingBox.Intersects = function (box0, box1) {
  18366. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18367. return false;
  18368. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18369. return false;
  18370. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18371. return false;
  18372. return true;
  18373. };
  18374. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18375. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18376. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18377. return (num <= (sphereRadius * sphereRadius));
  18378. };
  18379. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18380. for (var p = 0; p < 6; p++) {
  18381. for (var i = 0; i < 8; i++) {
  18382. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18383. return false;
  18384. }
  18385. }
  18386. }
  18387. return true;
  18388. };
  18389. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18390. for (var p = 0; p < 6; p++) {
  18391. var inCount = 8;
  18392. for (var i = 0; i < 8; i++) {
  18393. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18394. --inCount;
  18395. }
  18396. else {
  18397. break;
  18398. }
  18399. }
  18400. if (inCount === 0)
  18401. return false;
  18402. }
  18403. return true;
  18404. };
  18405. return BoundingBox;
  18406. }());
  18407. BABYLON.BoundingBox = BoundingBox;
  18408. })(BABYLON || (BABYLON = {}));
  18409. //# sourceMappingURL=babylon.boundingBox.js.map
  18410. var BABYLON;
  18411. (function (BABYLON) {
  18412. var computeBoxExtents = function (axis, box) {
  18413. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18414. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18415. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18416. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18417. var r = r0 + r1 + r2;
  18418. return {
  18419. min: p - r,
  18420. max: p + r
  18421. };
  18422. };
  18423. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18424. var axisOverlap = function (axis, box0, box1) {
  18425. var result0 = computeBoxExtents(axis, box0);
  18426. var result1 = computeBoxExtents(axis, box1);
  18427. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18428. };
  18429. var BoundingInfo = /** @class */ (function () {
  18430. function BoundingInfo(minimum, maximum) {
  18431. this.minimum = minimum;
  18432. this.maximum = maximum;
  18433. this._isLocked = false;
  18434. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18435. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18436. }
  18437. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18438. get: function () {
  18439. return this._isLocked;
  18440. },
  18441. set: function (value) {
  18442. this._isLocked = value;
  18443. },
  18444. enumerable: true,
  18445. configurable: true
  18446. });
  18447. // Methods
  18448. BoundingInfo.prototype.update = function (world) {
  18449. if (this._isLocked) {
  18450. return;
  18451. }
  18452. this.boundingBox._update(world);
  18453. this.boundingSphere._update(world);
  18454. };
  18455. /**
  18456. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18457. * @param center New center of the bounding info
  18458. * @param extend New extend of the bounding info
  18459. */
  18460. BoundingInfo.prototype.centerOn = function (center, extend) {
  18461. this.minimum = center.subtract(extend);
  18462. this.maximum = center.add(extend);
  18463. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18464. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18465. return this;
  18466. };
  18467. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18468. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18469. return false;
  18470. return this.boundingBox.isInFrustum(frustumPlanes);
  18471. };
  18472. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18473. /**
  18474. * Gets the world distance between the min and max points of the bounding box
  18475. */
  18476. get: function () {
  18477. var boundingBox = this.boundingBox;
  18478. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18479. return size.length();
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18485. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18486. };
  18487. BoundingInfo.prototype._checkCollision = function (collider) {
  18488. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18489. };
  18490. BoundingInfo.prototype.intersectsPoint = function (point) {
  18491. if (!this.boundingSphere.centerWorld) {
  18492. return false;
  18493. }
  18494. if (!this.boundingSphere.intersectsPoint(point)) {
  18495. return false;
  18496. }
  18497. if (!this.boundingBox.intersectsPoint(point)) {
  18498. return false;
  18499. }
  18500. return true;
  18501. };
  18502. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18503. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18504. return false;
  18505. }
  18506. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18507. return false;
  18508. }
  18509. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18510. return false;
  18511. }
  18512. if (!precise) {
  18513. return true;
  18514. }
  18515. var box0 = this.boundingBox;
  18516. var box1 = boundingInfo.boundingBox;
  18517. if (!axisOverlap(box0.directions[0], box0, box1))
  18518. return false;
  18519. if (!axisOverlap(box0.directions[1], box0, box1))
  18520. return false;
  18521. if (!axisOverlap(box0.directions[2], box0, box1))
  18522. return false;
  18523. if (!axisOverlap(box1.directions[0], box0, box1))
  18524. return false;
  18525. if (!axisOverlap(box1.directions[1], box0, box1))
  18526. return false;
  18527. if (!axisOverlap(box1.directions[2], box0, box1))
  18528. return false;
  18529. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18530. return false;
  18531. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18532. return false;
  18533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18534. return false;
  18535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18536. return false;
  18537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18538. return false;
  18539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18540. return false;
  18541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18542. return false;
  18543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18544. return false;
  18545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18546. return false;
  18547. return true;
  18548. };
  18549. return BoundingInfo;
  18550. }());
  18551. BABYLON.BoundingInfo = BoundingInfo;
  18552. })(BABYLON || (BABYLON = {}));
  18553. //# sourceMappingURL=babylon.boundingInfo.js.map
  18554. var BABYLON;
  18555. (function (BABYLON) {
  18556. var TransformNode = /** @class */ (function (_super) {
  18557. __extends(TransformNode, _super);
  18558. function TransformNode(name, scene, isPure) {
  18559. if (scene === void 0) { scene = null; }
  18560. if (isPure === void 0) { isPure = true; }
  18561. var _this = _super.call(this, name, scene) || this;
  18562. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18563. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18564. _this._up = new BABYLON.Vector3(0, 1, 0);
  18565. _this._right = new BABYLON.Vector3(1, 0, 0);
  18566. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18567. // Properties
  18568. _this._rotation = BABYLON.Vector3.Zero();
  18569. _this._scaling = BABYLON.Vector3.One();
  18570. _this._isDirty = false;
  18571. /**
  18572. * Set the billboard mode. Default is 0.
  18573. *
  18574. * | Value | Type | Description |
  18575. * | --- | --- | --- |
  18576. * | 0 | BILLBOARDMODE_NONE | |
  18577. * | 1 | BILLBOARDMODE_X | |
  18578. * | 2 | BILLBOARDMODE_Y | |
  18579. * | 4 | BILLBOARDMODE_Z | |
  18580. * | 7 | BILLBOARDMODE_ALL | |
  18581. *
  18582. */
  18583. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18584. _this.scalingDeterminant = 1;
  18585. _this.infiniteDistance = false;
  18586. /**
  18587. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18588. * By default the system will update normals to compensate
  18589. */
  18590. _this.ignoreNonUniformScaling = false;
  18591. _this.position = BABYLON.Vector3.Zero();
  18592. _this._localWorld = BABYLON.Matrix.Zero();
  18593. _this._worldMatrix = BABYLON.Matrix.Zero();
  18594. _this._worldMatrixDeterminant = 0;
  18595. _this._absolutePosition = BABYLON.Vector3.Zero();
  18596. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18597. _this._postMultiplyPivotMatrix = false;
  18598. _this._isWorldMatrixFrozen = false;
  18599. /**
  18600. * An event triggered after the world matrix is updated
  18601. */
  18602. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18603. _this._nonUniformScaling = false;
  18604. if (isPure) {
  18605. _this.getScene().addTransformNode(_this);
  18606. }
  18607. return _this;
  18608. }
  18609. /**
  18610. * Gets a string idenfifying the name of the class
  18611. * @returns "TransformNode" string
  18612. */
  18613. TransformNode.prototype.getClassName = function () {
  18614. return "TransformNode";
  18615. };
  18616. Object.defineProperty(TransformNode.prototype, "rotation", {
  18617. /**
  18618. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18619. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18620. * Default : (0.0, 0.0, 0.0)
  18621. */
  18622. get: function () {
  18623. return this._rotation;
  18624. },
  18625. set: function (newRotation) {
  18626. this._rotation = newRotation;
  18627. },
  18628. enumerable: true,
  18629. configurable: true
  18630. });
  18631. Object.defineProperty(TransformNode.prototype, "scaling", {
  18632. /**
  18633. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18634. * Default : (1.0, 1.0, 1.0)
  18635. */
  18636. get: function () {
  18637. return this._scaling;
  18638. },
  18639. /**
  18640. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18641. * Default : (1.0, 1.0, 1.0)
  18642. */
  18643. set: function (newScaling) {
  18644. this._scaling = newScaling;
  18645. },
  18646. enumerable: true,
  18647. configurable: true
  18648. });
  18649. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18650. /**
  18651. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18652. * It's null by default.
  18653. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18654. */
  18655. get: function () {
  18656. return this._rotationQuaternion;
  18657. },
  18658. set: function (quaternion) {
  18659. this._rotationQuaternion = quaternion;
  18660. //reset the rotation vector.
  18661. if (quaternion && this.rotation.length()) {
  18662. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18663. }
  18664. },
  18665. enumerable: true,
  18666. configurable: true
  18667. });
  18668. Object.defineProperty(TransformNode.prototype, "forward", {
  18669. /**
  18670. * The forward direction of that transform in world space.
  18671. */
  18672. get: function () {
  18673. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(TransformNode.prototype, "up", {
  18679. /**
  18680. * The up direction of that transform in world space.
  18681. */
  18682. get: function () {
  18683. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(TransformNode.prototype, "right", {
  18689. /**
  18690. * The right direction of that transform in world space.
  18691. */
  18692. get: function () {
  18693. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. /**
  18699. * Returns the latest update of the World matrix
  18700. * Returns a Matrix.
  18701. */
  18702. TransformNode.prototype.getWorldMatrix = function () {
  18703. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18704. this.computeWorldMatrix();
  18705. }
  18706. return this._worldMatrix;
  18707. };
  18708. /** @hidden */
  18709. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18710. return this._worldMatrixDeterminant;
  18711. };
  18712. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18713. /**
  18714. * Returns directly the latest state of the mesh World matrix.
  18715. * A Matrix is returned.
  18716. */
  18717. get: function () {
  18718. return this._worldMatrix;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. /**
  18724. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18728. this._poseMatrix.copyFrom(matrix);
  18729. return this;
  18730. };
  18731. /**
  18732. * Returns the mesh Pose matrix.
  18733. * Returned object : Matrix
  18734. */
  18735. TransformNode.prototype.getPoseMatrix = function () {
  18736. return this._poseMatrix;
  18737. };
  18738. TransformNode.prototype._isSynchronized = function () {
  18739. if (this._isDirty) {
  18740. return false;
  18741. }
  18742. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18743. return false;
  18744. if (this._cache.pivotMatrixUpdated) {
  18745. return false;
  18746. }
  18747. if (this.infiniteDistance) {
  18748. return false;
  18749. }
  18750. if (!this._cache.position.equals(this.position))
  18751. return false;
  18752. if (this.rotationQuaternion) {
  18753. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18754. return false;
  18755. }
  18756. if (!this._cache.rotation.equals(this.rotation))
  18757. return false;
  18758. if (!this._cache.scaling.equals(this.scaling))
  18759. return false;
  18760. return true;
  18761. };
  18762. TransformNode.prototype._initCache = function () {
  18763. _super.prototype._initCache.call(this);
  18764. this._cache.localMatrixUpdated = false;
  18765. this._cache.position = BABYLON.Vector3.Zero();
  18766. this._cache.scaling = BABYLON.Vector3.Zero();
  18767. this._cache.rotation = BABYLON.Vector3.Zero();
  18768. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18769. this._cache.billboardMode = -1;
  18770. };
  18771. TransformNode.prototype.markAsDirty = function (property) {
  18772. if (property === "rotation") {
  18773. this.rotationQuaternion = null;
  18774. }
  18775. this._currentRenderId = Number.MAX_VALUE;
  18776. this._isDirty = true;
  18777. return this;
  18778. };
  18779. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18780. /**
  18781. * Returns the current mesh absolute position.
  18782. * Retuns a Vector3.
  18783. */
  18784. get: function () {
  18785. return this._absolutePosition;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Sets a new matrix to apply before all other transformation
  18792. * @param matrix defines the transform matrix
  18793. * @returns the current TransformNode
  18794. */
  18795. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18796. return this.setPivotMatrix(matrix, false);
  18797. };
  18798. /**
  18799. * Sets a new pivot matrix to the current node
  18800. * @param matrix defines the new pivot matrix to use
  18801. * @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
  18802. * @returns the current TransformNode
  18803. */
  18804. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18805. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18806. this._pivotMatrix = matrix.clone();
  18807. this._cache.pivotMatrixUpdated = true;
  18808. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18809. if (this._postMultiplyPivotMatrix) {
  18810. if (!this._pivotMatrixInverse) {
  18811. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18812. }
  18813. else {
  18814. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18815. }
  18816. }
  18817. return this;
  18818. };
  18819. /**
  18820. * Returns the mesh pivot matrix.
  18821. * Default : Identity.
  18822. * A Matrix is returned.
  18823. */
  18824. TransformNode.prototype.getPivotMatrix = function () {
  18825. return this._pivotMatrix;
  18826. };
  18827. /**
  18828. * Prevents the World matrix to be computed any longer.
  18829. * Returns the TransformNode.
  18830. */
  18831. TransformNode.prototype.freezeWorldMatrix = function () {
  18832. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18833. this.computeWorldMatrix(true);
  18834. this._isWorldMatrixFrozen = true;
  18835. return this;
  18836. };
  18837. /**
  18838. * Allows back the World matrix computation.
  18839. * Returns the TransformNode.
  18840. */
  18841. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18842. this._isWorldMatrixFrozen = false;
  18843. this.computeWorldMatrix(true);
  18844. return this;
  18845. };
  18846. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18847. /**
  18848. * True if the World matrix has been frozen.
  18849. * Returns a boolean.
  18850. */
  18851. get: function () {
  18852. return this._isWorldMatrixFrozen;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. /**
  18858. * Retuns the mesh absolute position in the World.
  18859. * Returns a Vector3.
  18860. */
  18861. TransformNode.prototype.getAbsolutePosition = function () {
  18862. this.computeWorldMatrix();
  18863. return this._absolutePosition;
  18864. };
  18865. /**
  18866. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18867. * Returns the TransformNode.
  18868. */
  18869. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18870. if (!absolutePosition) {
  18871. return this;
  18872. }
  18873. var absolutePositionX;
  18874. var absolutePositionY;
  18875. var absolutePositionZ;
  18876. if (absolutePosition.x === undefined) {
  18877. if (arguments.length < 3) {
  18878. return this;
  18879. }
  18880. absolutePositionX = arguments[0];
  18881. absolutePositionY = arguments[1];
  18882. absolutePositionZ = arguments[2];
  18883. }
  18884. else {
  18885. absolutePositionX = absolutePosition.x;
  18886. absolutePositionY = absolutePosition.y;
  18887. absolutePositionZ = absolutePosition.z;
  18888. }
  18889. if (this.parent) {
  18890. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18891. invertParentWorldMatrix.invert();
  18892. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18893. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18894. }
  18895. else {
  18896. this.position.x = absolutePositionX;
  18897. this.position.y = absolutePositionY;
  18898. this.position.z = absolutePositionZ;
  18899. }
  18900. return this;
  18901. };
  18902. /**
  18903. * Sets the mesh position in its local space.
  18904. * Returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18907. this.computeWorldMatrix();
  18908. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18909. return this;
  18910. };
  18911. /**
  18912. * Returns the mesh position in the local space from the current World matrix values.
  18913. * Returns a new Vector3.
  18914. */
  18915. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18916. this.computeWorldMatrix();
  18917. var invLocalWorldMatrix = this._localWorld.clone();
  18918. invLocalWorldMatrix.invert();
  18919. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18920. };
  18921. /**
  18922. * Translates the mesh along the passed Vector3 in its local space.
  18923. * Returns the TransformNode.
  18924. */
  18925. TransformNode.prototype.locallyTranslate = function (vector3) {
  18926. this.computeWorldMatrix(true);
  18927. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18928. return this;
  18929. };
  18930. /**
  18931. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18932. * @param targetPoint the position (must be in same space as current mesh) to look at
  18933. * @param yawCor optional yaw (y-axis) correction in radians
  18934. * @param pitchCor optional pitch (x-axis) correction in radians
  18935. * @param rollCor optional roll (z-axis) correction in radians
  18936. * @param space the choosen space of the target
  18937. * @returns the TransformNode.
  18938. */
  18939. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18940. if (yawCor === void 0) { yawCor = 0; }
  18941. if (pitchCor === void 0) { pitchCor = 0; }
  18942. if (rollCor === void 0) { rollCor = 0; }
  18943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18944. var dv = TransformNode._lookAtVectorCache;
  18945. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18946. targetPoint.subtractToRef(pos, dv);
  18947. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18948. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18949. var pitch = Math.atan2(dv.y, len);
  18950. if (this.rotationQuaternion) {
  18951. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18952. }
  18953. else {
  18954. this.rotation.x = pitch + pitchCor;
  18955. this.rotation.y = yaw + yawCor;
  18956. this.rotation.z = rollCor;
  18957. }
  18958. return this;
  18959. };
  18960. /**
  18961. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18962. * This Vector3 is expressed in the World space.
  18963. */
  18964. TransformNode.prototype.getDirection = function (localAxis) {
  18965. var result = BABYLON.Vector3.Zero();
  18966. this.getDirectionToRef(localAxis, result);
  18967. return result;
  18968. };
  18969. /**
  18970. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18971. * localAxis is expressed in the mesh local space.
  18972. * result is computed in the Wordl space from the mesh World matrix.
  18973. * Returns the TransformNode.
  18974. */
  18975. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18976. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18977. return this;
  18978. };
  18979. /**
  18980. * Sets a new pivot point to the current node
  18981. * @param point defines the new pivot point to use
  18982. * @param space defines if the point is in world or local space (local by default)
  18983. * @returns the current TransformNode
  18984. */
  18985. TransformNode.prototype.setPivotPoint = function (point, space) {
  18986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18987. if (this.getScene().getRenderId() == 0) {
  18988. this.computeWorldMatrix(true);
  18989. }
  18990. var wm = this.getWorldMatrix();
  18991. if (space == BABYLON.Space.WORLD) {
  18992. var tmat = BABYLON.Tmp.Matrix[0];
  18993. wm.invertToRef(tmat);
  18994. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18995. }
  18996. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18997. };
  18998. /**
  18999. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19000. */
  19001. TransformNode.prototype.getPivotPoint = function () {
  19002. var point = BABYLON.Vector3.Zero();
  19003. this.getPivotPointToRef(point);
  19004. return point;
  19005. };
  19006. /**
  19007. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19008. * Returns the TransformNode.
  19009. */
  19010. TransformNode.prototype.getPivotPointToRef = function (result) {
  19011. result.x = -this._pivotMatrix.m[12];
  19012. result.y = -this._pivotMatrix.m[13];
  19013. result.z = -this._pivotMatrix.m[14];
  19014. return this;
  19015. };
  19016. /**
  19017. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19018. */
  19019. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19020. var point = BABYLON.Vector3.Zero();
  19021. this.getAbsolutePivotPointToRef(point);
  19022. return point;
  19023. };
  19024. /**
  19025. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19026. * Returns the TransformNode.
  19027. */
  19028. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19029. result.x = this._pivotMatrix.m[12];
  19030. result.y = this._pivotMatrix.m[13];
  19031. result.z = this._pivotMatrix.m[14];
  19032. this.getPivotPointToRef(result);
  19033. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19034. return this;
  19035. };
  19036. /**
  19037. * Defines the passed node as the parent of the current node.
  19038. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19039. * Returns the TransformNode.
  19040. */
  19041. TransformNode.prototype.setParent = function (node) {
  19042. if (!node && !this.parent) {
  19043. return this;
  19044. }
  19045. if (!node) {
  19046. var rotation = BABYLON.Tmp.Quaternion[0];
  19047. var position = BABYLON.Tmp.Vector3[0];
  19048. var scale = BABYLON.Tmp.Vector3[1];
  19049. if (this.parent && this.parent.computeWorldMatrix) {
  19050. this.parent.computeWorldMatrix(true);
  19051. }
  19052. this.computeWorldMatrix(true);
  19053. this.getWorldMatrix().decompose(scale, rotation, position);
  19054. if (this.rotationQuaternion) {
  19055. this.rotationQuaternion.copyFrom(rotation);
  19056. }
  19057. else {
  19058. rotation.toEulerAnglesToRef(this.rotation);
  19059. }
  19060. this.scaling.x = scale.x;
  19061. this.scaling.y = scale.y;
  19062. this.scaling.z = scale.z;
  19063. this.position.x = position.x;
  19064. this.position.y = position.y;
  19065. this.position.z = position.z;
  19066. }
  19067. else {
  19068. var rotation = BABYLON.Tmp.Quaternion[0];
  19069. var position = BABYLON.Tmp.Vector3[0];
  19070. var scale = BABYLON.Tmp.Vector3[1];
  19071. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19072. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19073. this.computeWorldMatrix(true);
  19074. node.computeWorldMatrix(true);
  19075. node.getWorldMatrix().invertToRef(invParentMatrix);
  19076. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19077. diffMatrix.decompose(scale, rotation, position);
  19078. if (this.rotationQuaternion) {
  19079. this.rotationQuaternion.copyFrom(rotation);
  19080. }
  19081. else {
  19082. rotation.toEulerAnglesToRef(this.rotation);
  19083. }
  19084. this.position.x = position.x;
  19085. this.position.y = position.y;
  19086. this.position.z = position.z;
  19087. this.scaling.x = scale.x;
  19088. this.scaling.y = scale.y;
  19089. this.scaling.z = scale.z;
  19090. }
  19091. this.parent = node;
  19092. return this;
  19093. };
  19094. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19095. get: function () {
  19096. return this._nonUniformScaling;
  19097. },
  19098. enumerable: true,
  19099. configurable: true
  19100. });
  19101. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19102. if (this._nonUniformScaling === value) {
  19103. return false;
  19104. }
  19105. this._nonUniformScaling = value;
  19106. return true;
  19107. };
  19108. /**
  19109. * Attach the current TransformNode to another TransformNode associated with a bone
  19110. * @param bone Bone affecting the TransformNode
  19111. * @param affectedTransformNode TransformNode associated with the bone
  19112. */
  19113. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19114. this._transformToBoneReferal = affectedTransformNode;
  19115. this.parent = bone;
  19116. if (bone.getWorldMatrix().determinant() < 0) {
  19117. this.scalingDeterminant *= -1;
  19118. }
  19119. return this;
  19120. };
  19121. TransformNode.prototype.detachFromBone = function () {
  19122. if (!this.parent) {
  19123. return this;
  19124. }
  19125. if (this.parent.getWorldMatrix().determinant() < 0) {
  19126. this.scalingDeterminant *= -1;
  19127. }
  19128. this._transformToBoneReferal = null;
  19129. this.parent = null;
  19130. return this;
  19131. };
  19132. /**
  19133. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19134. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19135. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19136. * The passed axis is also normalized.
  19137. * Returns the TransformNode.
  19138. */
  19139. TransformNode.prototype.rotate = function (axis, amount, space) {
  19140. axis.normalize();
  19141. if (!this.rotationQuaternion) {
  19142. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19143. this.rotation = BABYLON.Vector3.Zero();
  19144. }
  19145. var rotationQuaternion;
  19146. if (!space || space === BABYLON.Space.LOCAL) {
  19147. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19148. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19149. }
  19150. else {
  19151. if (this.parent) {
  19152. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19153. invertParentWorldMatrix.invert();
  19154. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19155. }
  19156. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19157. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19158. }
  19159. return this;
  19160. };
  19161. /**
  19162. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19163. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19164. * The passed axis is also normalized.
  19165. * Returns the TransformNode.
  19166. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19167. */
  19168. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19169. axis.normalize();
  19170. if (!this.rotationQuaternion) {
  19171. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19172. this.rotation.copyFromFloats(0, 0, 0);
  19173. }
  19174. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19175. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19176. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19177. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19178. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19179. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19180. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19181. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19182. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19183. return this;
  19184. };
  19185. /**
  19186. * Translates the mesh along the axis vector for the passed distance in the given space.
  19187. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19188. * Returns the TransformNode.
  19189. */
  19190. TransformNode.prototype.translate = function (axis, distance, space) {
  19191. var displacementVector = axis.scale(distance);
  19192. if (!space || space === BABYLON.Space.LOCAL) {
  19193. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19194. this.setPositionWithLocalVector(tempV3);
  19195. }
  19196. else {
  19197. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19198. }
  19199. return this;
  19200. };
  19201. /**
  19202. * Adds a rotation step to the mesh current rotation.
  19203. * x, y, z are Euler angles expressed in radians.
  19204. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19205. * This means this rotation is made in the mesh local space only.
  19206. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19207. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19208. * ```javascript
  19209. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19210. * ```
  19211. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19212. * 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.
  19213. * Returns the TransformNode.
  19214. */
  19215. TransformNode.prototype.addRotation = function (x, y, z) {
  19216. var rotationQuaternion;
  19217. if (this.rotationQuaternion) {
  19218. rotationQuaternion = this.rotationQuaternion;
  19219. }
  19220. else {
  19221. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19222. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19223. }
  19224. var accumulation = BABYLON.Tmp.Quaternion[0];
  19225. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19226. rotationQuaternion.multiplyInPlace(accumulation);
  19227. if (!this.rotationQuaternion) {
  19228. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19229. }
  19230. return this;
  19231. };
  19232. /**
  19233. * Computes the mesh World matrix and returns it.
  19234. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19235. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19236. * If the parameter `force`is set to `true`, the actual computation is done.
  19237. * Returns the mesh World Matrix.
  19238. */
  19239. TransformNode.prototype.computeWorldMatrix = function (force) {
  19240. if (this._isWorldMatrixFrozen) {
  19241. return this._worldMatrix;
  19242. }
  19243. if (!force && this.isSynchronized(true)) {
  19244. this._currentRenderId = this.getScene().getRenderId();
  19245. return this._worldMatrix;
  19246. }
  19247. this._cache.position.copyFrom(this.position);
  19248. this._cache.scaling.copyFrom(this.scaling);
  19249. this._cache.pivotMatrixUpdated = false;
  19250. this._cache.billboardMode = this.billboardMode;
  19251. this._currentRenderId = this.getScene().getRenderId();
  19252. this._childRenderId = this.getScene().getRenderId();
  19253. this._isDirty = false;
  19254. // Scaling
  19255. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19256. // Rotation
  19257. //rotate, if quaternion is set and rotation was used
  19258. if (this.rotationQuaternion) {
  19259. var len = this.rotation.length();
  19260. if (len) {
  19261. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19262. this.rotation.copyFromFloats(0, 0, 0);
  19263. }
  19264. }
  19265. if (this.rotationQuaternion) {
  19266. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19267. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19268. }
  19269. else {
  19270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19271. this._cache.rotation.copyFrom(this.rotation);
  19272. }
  19273. // Translation
  19274. var camera = this.getScene().activeCamera;
  19275. if (this.infiniteDistance && !this.parent && camera) {
  19276. var cameraWorldMatrix = camera.getWorldMatrix();
  19277. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19278. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19279. }
  19280. else {
  19281. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19282. }
  19283. // Composing transformations
  19284. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19285. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19286. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19287. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19288. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19289. // Need to decompose each rotation here
  19290. var currentPosition = BABYLON.Tmp.Vector3[3];
  19291. if (this.parent && this.parent.getWorldMatrix) {
  19292. if (this._transformToBoneReferal) {
  19293. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19295. }
  19296. else {
  19297. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19298. }
  19299. }
  19300. else {
  19301. currentPosition.copyFrom(this.position);
  19302. }
  19303. currentPosition.subtractInPlace(camera.globalPosition);
  19304. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19305. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19306. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19307. }
  19308. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19309. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19310. }
  19311. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19312. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19313. }
  19314. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19315. }
  19316. else {
  19317. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19318. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19319. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19320. }
  19321. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19322. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19323. }
  19324. // Local world
  19325. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19326. // Parent
  19327. if (this.parent && this.parent.getWorldMatrix) {
  19328. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19329. if (this._transformToBoneReferal) {
  19330. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19331. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19332. }
  19333. else {
  19334. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19335. }
  19336. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19337. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19338. this._worldMatrix.copyFrom(this._localWorld);
  19339. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19340. }
  19341. else {
  19342. if (this._transformToBoneReferal) {
  19343. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19344. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19345. }
  19346. else {
  19347. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19348. }
  19349. }
  19350. this._markSyncedWithParent();
  19351. }
  19352. else {
  19353. this._worldMatrix.copyFrom(this._localWorld);
  19354. }
  19355. // Post multiply inverse of pivotMatrix
  19356. if (this._postMultiplyPivotMatrix) {
  19357. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19358. }
  19359. // Normal matrix
  19360. if (!this.ignoreNonUniformScaling) {
  19361. if (this.scaling.isNonUniform) {
  19362. this._updateNonUniformScalingState(true);
  19363. }
  19364. else if (this.parent && this.parent._nonUniformScaling) {
  19365. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19366. }
  19367. else {
  19368. this._updateNonUniformScalingState(false);
  19369. }
  19370. }
  19371. else {
  19372. this._updateNonUniformScalingState(false);
  19373. }
  19374. this._afterComputeWorldMatrix();
  19375. // Absolute position
  19376. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19377. // Callbacks
  19378. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19379. if (!this._poseMatrix) {
  19380. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19381. }
  19382. // Cache the determinant
  19383. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19384. return this._worldMatrix;
  19385. };
  19386. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19387. };
  19388. /**
  19389. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19390. * @param func: callback function to add
  19391. *
  19392. * Returns the TransformNode.
  19393. */
  19394. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19395. this.onAfterWorldMatrixUpdateObservable.add(func);
  19396. return this;
  19397. };
  19398. /**
  19399. * Removes a registered callback function.
  19400. * Returns the TransformNode.
  19401. */
  19402. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19403. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19404. return this;
  19405. };
  19406. /**
  19407. * Clone the current transform node
  19408. * Returns the new transform node
  19409. * @param name Name of the new clone
  19410. * @param newParent New parent for the clone
  19411. * @param doNotCloneChildren Do not clone children hierarchy
  19412. */
  19413. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19414. var _this = this;
  19415. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19416. result.name = name;
  19417. result.id = name;
  19418. if (newParent) {
  19419. result.parent = newParent;
  19420. }
  19421. if (!doNotCloneChildren) {
  19422. // Children
  19423. var directDescendants = this.getDescendants(true);
  19424. for (var index = 0; index < directDescendants.length; index++) {
  19425. var child = directDescendants[index];
  19426. if (child.clone) {
  19427. child.clone(name + "." + child.name, result);
  19428. }
  19429. }
  19430. }
  19431. return result;
  19432. };
  19433. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19434. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19435. serializationObject.type = this.getClassName();
  19436. // Parent
  19437. if (this.parent) {
  19438. serializationObject.parentId = this.parent.id;
  19439. }
  19440. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19441. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19442. }
  19443. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19444. serializationObject.isEnabled = this.isEnabled();
  19445. // Parent
  19446. if (this.parent) {
  19447. serializationObject.parentId = this.parent.id;
  19448. }
  19449. return serializationObject;
  19450. };
  19451. // Statics
  19452. /**
  19453. * Returns a new TransformNode object parsed from the source provided.
  19454. * The parameter `parsedMesh` is the source.
  19455. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19456. */
  19457. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19458. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19459. if (BABYLON.Tags) {
  19460. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19461. }
  19462. if (parsedTransformNode.localMatrix) {
  19463. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19464. }
  19465. else if (parsedTransformNode.pivotMatrix) {
  19466. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19467. }
  19468. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19469. // Parent
  19470. if (parsedTransformNode.parentId) {
  19471. transformNode._waitingParentId = parsedTransformNode.parentId;
  19472. }
  19473. return transformNode;
  19474. };
  19475. /**
  19476. * Releases resources associated with this transform node.
  19477. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19478. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19479. */
  19480. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19481. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19482. // Animations
  19483. this.getScene().stopAnimation(this);
  19484. // Remove from scene
  19485. this.getScene().removeTransformNode(this);
  19486. this.onAfterWorldMatrixUpdateObservable.clear();
  19487. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19488. };
  19489. // Statics
  19490. TransformNode.BILLBOARDMODE_NONE = 0;
  19491. TransformNode.BILLBOARDMODE_X = 1;
  19492. TransformNode.BILLBOARDMODE_Y = 2;
  19493. TransformNode.BILLBOARDMODE_Z = 4;
  19494. TransformNode.BILLBOARDMODE_ALL = 7;
  19495. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19496. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19497. __decorate([
  19498. BABYLON.serializeAsVector3()
  19499. ], TransformNode.prototype, "_rotation", void 0);
  19500. __decorate([
  19501. BABYLON.serializeAsQuaternion()
  19502. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19503. __decorate([
  19504. BABYLON.serializeAsVector3()
  19505. ], TransformNode.prototype, "_scaling", void 0);
  19506. __decorate([
  19507. BABYLON.serialize()
  19508. ], TransformNode.prototype, "billboardMode", void 0);
  19509. __decorate([
  19510. BABYLON.serialize()
  19511. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19512. __decorate([
  19513. BABYLON.serialize()
  19514. ], TransformNode.prototype, "infiniteDistance", void 0);
  19515. __decorate([
  19516. BABYLON.serialize()
  19517. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19518. __decorate([
  19519. BABYLON.serializeAsVector3()
  19520. ], TransformNode.prototype, "position", void 0);
  19521. return TransformNode;
  19522. }(BABYLON.Node));
  19523. BABYLON.TransformNode = TransformNode;
  19524. })(BABYLON || (BABYLON = {}));
  19525. //# sourceMappingURL=babylon.transformNode.js.map
  19526. var BABYLON;
  19527. (function (BABYLON) {
  19528. /**
  19529. * Class used to store all common mesh properties
  19530. */
  19531. var AbstractMesh = /** @class */ (function (_super) {
  19532. __extends(AbstractMesh, _super);
  19533. // Constructor
  19534. /**
  19535. * Creates a new AbstractMesh
  19536. * @param name defines the name of the mesh
  19537. * @param scene defines the hosting scene
  19538. */
  19539. function AbstractMesh(name, scene) {
  19540. if (scene === void 0) { scene = null; }
  19541. var _this = _super.call(this, name, scene, false) || this;
  19542. _this._facetNb = 0; // facet number
  19543. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19544. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19545. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19546. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19547. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19548. _this._subDiv = {
  19549. max: 1,
  19550. X: 1,
  19551. Y: 1,
  19552. Z: 1
  19553. };
  19554. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19555. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19556. // Events
  19557. /**
  19558. * An event triggered when this mesh collides with another one
  19559. */
  19560. _this.onCollideObservable = new BABYLON.Observable();
  19561. /**
  19562. * An event triggered when the collision's position changes
  19563. */
  19564. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19565. /**
  19566. * An event triggered when material is changed
  19567. */
  19568. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19569. // Properties
  19570. /**
  19571. * Gets or sets the orientation for POV movement & rotation
  19572. */
  19573. _this.definedFacingForward = true;
  19574. /**
  19575. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19576. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19577. * * 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.
  19578. * @see http://doc.babylonjs.com/features/occlusionquery
  19579. */
  19580. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19581. /**
  19582. * 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:
  19583. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19584. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19585. * * 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.
  19586. * @see http://doc.babylonjs.com/features/occlusionquery
  19587. */
  19588. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19589. /**
  19590. * 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.
  19591. * The default value is -1 which means don't break the query and wait till the result
  19592. * @see http://doc.babylonjs.com/features/occlusionquery
  19593. */
  19594. _this.occlusionRetryCount = -1;
  19595. _this._occlusionInternalRetryCounter = 0;
  19596. _this._isOccluded = false;
  19597. _this._isOcclusionQueryInProgress = false;
  19598. _this._visibility = 1.0;
  19599. /** Gets or sets the alpha index used to sort transparent meshes
  19600. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19601. */
  19602. _this.alphaIndex = Number.MAX_VALUE;
  19603. /**
  19604. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19605. */
  19606. _this.isVisible = true;
  19607. /**
  19608. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19609. */
  19610. _this.isPickable = true;
  19611. /**
  19612. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19613. */
  19614. _this.showBoundingBox = false;
  19615. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19616. _this.showSubMeshesBoundingBox = false;
  19617. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19618. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19619. */
  19620. _this.isBlocker = false;
  19621. /**
  19622. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19623. */
  19624. _this.enablePointerMoveEvents = false;
  19625. /**
  19626. * Specifies the rendering group id for this mesh (0 by default)
  19627. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19628. */
  19629. _this.renderingGroupId = 0;
  19630. _this._receiveShadows = false;
  19631. /**
  19632. * Gets or sets a boolean indicating if the outline must be rendered as well
  19633. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19634. */
  19635. _this.renderOutline = false;
  19636. /** Defines color to use when rendering outline */
  19637. _this.outlineColor = BABYLON.Color3.Red();
  19638. /** Define width to use when rendering outline */
  19639. _this.outlineWidth = 0.02;
  19640. /**
  19641. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19642. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19643. */
  19644. _this.renderOverlay = false;
  19645. /** Defines color to use when rendering overlay */
  19646. _this.overlayColor = BABYLON.Color3.Red();
  19647. /** Defines alpha to use when rendering overlay */
  19648. _this.overlayAlpha = 0.5;
  19649. _this._hasVertexAlpha = false;
  19650. _this._useVertexColors = true;
  19651. _this._computeBonesUsingShaders = true;
  19652. _this._numBoneInfluencers = 4;
  19653. _this._applyFog = true;
  19654. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19655. _this.useOctreeForRenderingSelection = true;
  19656. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19657. _this.useOctreeForPicking = true;
  19658. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19659. _this.useOctreeForCollisions = true;
  19660. _this._layerMask = 0x0FFFFFFF;
  19661. /**
  19662. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19663. */
  19664. _this.alwaysSelectAsActiveMesh = false;
  19665. /**
  19666. * Gets or sets the current action manager
  19667. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19668. */
  19669. _this.actionManager = null;
  19670. /**
  19671. * Gets or sets impostor used for physic simulation
  19672. * @see http://doc.babylonjs.com/features/physics_engine
  19673. */
  19674. _this.physicsImpostor = null;
  19675. // Collisions
  19676. _this._checkCollisions = false;
  19677. _this._collisionMask = -1;
  19678. _this._collisionGroup = -1;
  19679. /**
  19680. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19681. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19682. */
  19683. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19684. /**
  19685. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19686. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19687. */
  19688. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19689. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19690. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19691. // Edges
  19692. /**
  19693. * Defines edge width used when edgesRenderer is enabled
  19694. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19695. */
  19696. _this.edgesWidth = 1;
  19697. /**
  19698. * Defines edge color used when edgesRenderer is enabled
  19699. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19700. */
  19701. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19702. // Cache
  19703. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19704. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19705. /** @hidden */
  19706. _this._renderId = 0;
  19707. /** @hidden */
  19708. _this._intersectionsInProgress = new Array();
  19709. /** @hidden */
  19710. _this._unIndexed = false;
  19711. /** @hidden */
  19712. _this._lightSources = new Array();
  19713. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19714. if (collidedMesh === void 0) { collidedMesh = null; }
  19715. //TODO move this to the collision coordinator!
  19716. if (_this.getScene().workerCollisions)
  19717. newPosition.multiplyInPlace(_this._collider._radius);
  19718. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19719. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19720. _this.position.addInPlace(_this._diffPositionForCollisions);
  19721. }
  19722. if (collidedMesh) {
  19723. _this.onCollideObservable.notifyObservers(collidedMesh);
  19724. }
  19725. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19726. };
  19727. _this.getScene().addMesh(_this);
  19728. _this._resyncLightSources();
  19729. return _this;
  19730. }
  19731. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19732. /**
  19733. * No billboard
  19734. */
  19735. get: function () {
  19736. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19742. /** Billboard on X axis */
  19743. get: function () {
  19744. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19750. /** Billboard on Y axis */
  19751. get: function () {
  19752. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19758. /** Billboard on Z axis */
  19759. get: function () {
  19760. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19766. /** Billboard on all axes */
  19767. get: function () {
  19768. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19774. /**
  19775. * Gets the number of facets in the mesh
  19776. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19777. */
  19778. get: function () {
  19779. return this._facetNb;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19785. /**
  19786. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19787. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19788. */
  19789. get: function () {
  19790. return this._partitioningSubdivisions;
  19791. },
  19792. set: function (nb) {
  19793. this._partitioningSubdivisions = nb;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19799. /**
  19800. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19801. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19802. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19803. */
  19804. get: function () {
  19805. return this._partitioningBBoxRatio;
  19806. },
  19807. set: function (ratio) {
  19808. this._partitioningBBoxRatio = ratio;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19814. /**
  19815. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19816. * Works only for updatable meshes.
  19817. * Doesn't work with multi-materials
  19818. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19819. */
  19820. get: function () {
  19821. return this._facetDepthSort;
  19822. },
  19823. set: function (sort) {
  19824. this._facetDepthSort = sort;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19830. /**
  19831. * The location (Vector3) where the facet depth sort must be computed from.
  19832. * By default, the active camera position.
  19833. * Used only when facet depth sort is enabled
  19834. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19835. */
  19836. get: function () {
  19837. return this._facetDepthSortFrom;
  19838. },
  19839. set: function (location) {
  19840. this._facetDepthSortFrom = location;
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19846. /**
  19847. * gets a boolean indicating if facetData is enabled
  19848. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19849. */
  19850. get: function () {
  19851. return this._facetDataEnabled;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. /** @hidden */
  19857. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19858. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19859. return false;
  19860. }
  19861. this._markSubMeshesAsMiscDirty();
  19862. return true;
  19863. };
  19864. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19865. /** Set a function to call when this mesh collides with another one */
  19866. set: function (callback) {
  19867. if (this._onCollideObserver) {
  19868. this.onCollideObservable.remove(this._onCollideObserver);
  19869. }
  19870. this._onCollideObserver = this.onCollideObservable.add(callback);
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19876. /** Set a function to call when the collision's position changes */
  19877. set: function (callback) {
  19878. if (this._onCollisionPositionChangeObserver) {
  19879. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19880. }
  19881. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19887. /**
  19888. * 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
  19889. * @see http://doc.babylonjs.com/features/occlusionquery
  19890. */
  19891. get: function () {
  19892. return this._isOccluded;
  19893. },
  19894. set: function (value) {
  19895. this._isOccluded = value;
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19901. /**
  19902. * Flag to check the progress status of the query
  19903. * @see http://doc.babylonjs.com/features/occlusionquery
  19904. */
  19905. get: function () {
  19906. return this._isOcclusionQueryInProgress;
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19912. /**
  19913. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19914. */
  19915. get: function () {
  19916. return this._visibility;
  19917. },
  19918. /**
  19919. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19920. */
  19921. set: function (value) {
  19922. if (this._visibility === value) {
  19923. return;
  19924. }
  19925. this._visibility = value;
  19926. this._markSubMeshesAsMiscDirty();
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Object.defineProperty(AbstractMesh.prototype, "material", {
  19932. /** Gets or sets current material */
  19933. get: function () {
  19934. return this._material;
  19935. },
  19936. set: function (value) {
  19937. if (this._material === value) {
  19938. return;
  19939. }
  19940. this._material = value;
  19941. if (this.onMaterialChangedObservable.hasObservers) {
  19942. this.onMaterialChangedObservable.notifyObservers(this);
  19943. }
  19944. if (!this.subMeshes) {
  19945. return;
  19946. }
  19947. this._unBindEffect();
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19953. /**
  19954. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19955. * @see http://doc.babylonjs.com/babylon101/shadows
  19956. */
  19957. get: function () {
  19958. return this._receiveShadows;
  19959. },
  19960. set: function (value) {
  19961. if (this._receiveShadows === value) {
  19962. return;
  19963. }
  19964. this._receiveShadows = value;
  19965. this._markSubMeshesAsLightDirty();
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19971. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19972. get: function () {
  19973. return this._hasVertexAlpha;
  19974. },
  19975. set: function (value) {
  19976. if (this._hasVertexAlpha === value) {
  19977. return;
  19978. }
  19979. this._hasVertexAlpha = value;
  19980. this._markSubMeshesAsAttributesDirty();
  19981. this._markSubMeshesAsMiscDirty();
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19987. /** 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) */
  19988. get: function () {
  19989. return this._useVertexColors;
  19990. },
  19991. set: function (value) {
  19992. if (this._useVertexColors === value) {
  19993. return;
  19994. }
  19995. this._useVertexColors = value;
  19996. this._markSubMeshesAsAttributesDirty();
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20002. /**
  20003. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20004. */
  20005. get: function () {
  20006. return this._computeBonesUsingShaders;
  20007. },
  20008. set: function (value) {
  20009. if (this._computeBonesUsingShaders === value) {
  20010. return;
  20011. }
  20012. this._computeBonesUsingShaders = value;
  20013. this._markSubMeshesAsAttributesDirty();
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20019. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20020. get: function () {
  20021. return this._numBoneInfluencers;
  20022. },
  20023. set: function (value) {
  20024. if (this._numBoneInfluencers === value) {
  20025. return;
  20026. }
  20027. this._numBoneInfluencers = value;
  20028. this._markSubMeshesAsAttributesDirty();
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20034. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20035. get: function () {
  20036. return this._applyFog;
  20037. },
  20038. set: function (value) {
  20039. if (this._applyFog === value) {
  20040. return;
  20041. }
  20042. this._applyFog = value;
  20043. this._markSubMeshesAsMiscDirty();
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20049. /**
  20050. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20051. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20052. */
  20053. get: function () {
  20054. return this._layerMask;
  20055. },
  20056. set: function (value) {
  20057. if (value === this._layerMask) {
  20058. return;
  20059. }
  20060. this._layerMask = value;
  20061. this._resyncLightSources();
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20067. /**
  20068. * Gets or sets a collision mask used to mask collisions (default is -1).
  20069. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20070. */
  20071. get: function () {
  20072. return this._collisionMask;
  20073. },
  20074. set: function (mask) {
  20075. this._collisionMask = !isNaN(mask) ? mask : -1;
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20081. /**
  20082. * Gets or sets the current collision group mask (-1 by default).
  20083. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20084. */
  20085. get: function () {
  20086. return this._collisionGroup;
  20087. },
  20088. set: function (mask) {
  20089. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20095. /** @hidden */
  20096. get: function () {
  20097. return null;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20103. get: function () {
  20104. return this._skeleton;
  20105. },
  20106. /**
  20107. * Gets or sets a skeleton to apply skining transformations
  20108. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20109. */
  20110. set: function (value) {
  20111. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20112. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20113. }
  20114. if (value && value.needInitialSkinMatrix) {
  20115. value._registerMeshWithPoseMatrix(this);
  20116. }
  20117. this._skeleton = value;
  20118. if (!this._skeleton) {
  20119. this._bonesTransformMatrices = null;
  20120. }
  20121. this._markSubMeshesAsAttributesDirty();
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. /**
  20127. * Returns the string "AbstractMesh"
  20128. * @returns "AbstractMesh"
  20129. */
  20130. AbstractMesh.prototype.getClassName = function () {
  20131. return "AbstractMesh";
  20132. };
  20133. /**
  20134. * Gets a string representation of the current mesh
  20135. * @param fullDetails defines a boolean indicating if full details must be included
  20136. * @returns a string representation of the current mesh
  20137. */
  20138. AbstractMesh.prototype.toString = function (fullDetails) {
  20139. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20140. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20141. if (this._skeleton) {
  20142. ret += ", skeleton: " + this._skeleton.name;
  20143. }
  20144. if (fullDetails) {
  20145. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20146. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20147. }
  20148. return ret;
  20149. };
  20150. /** @hidden */
  20151. AbstractMesh.prototype._rebuild = function () {
  20152. if (this._occlusionQuery) {
  20153. this._occlusionQuery = null;
  20154. }
  20155. if (this._edgesRenderer) {
  20156. this._edgesRenderer._rebuild();
  20157. }
  20158. if (!this.subMeshes) {
  20159. return;
  20160. }
  20161. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20162. var subMesh = _a[_i];
  20163. subMesh._rebuild();
  20164. }
  20165. };
  20166. /** @hidden */
  20167. AbstractMesh.prototype._resyncLightSources = function () {
  20168. this._lightSources.length = 0;
  20169. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20170. var light = _a[_i];
  20171. if (!light.isEnabled()) {
  20172. continue;
  20173. }
  20174. if (light.canAffectMesh(this)) {
  20175. this._lightSources.push(light);
  20176. }
  20177. }
  20178. this._markSubMeshesAsLightDirty();
  20179. };
  20180. /** @hidden */
  20181. AbstractMesh.prototype._resyncLighSource = function (light) {
  20182. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20183. var index = this._lightSources.indexOf(light);
  20184. if (index === -1) {
  20185. if (!isIn) {
  20186. return;
  20187. }
  20188. this._lightSources.push(light);
  20189. }
  20190. else {
  20191. if (isIn) {
  20192. return;
  20193. }
  20194. this._lightSources.splice(index, 1);
  20195. }
  20196. this._markSubMeshesAsLightDirty();
  20197. };
  20198. /** @hidden */
  20199. AbstractMesh.prototype._unBindEffect = function () {
  20200. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20201. var subMesh = _a[_i];
  20202. subMesh.setEffect(null);
  20203. }
  20204. };
  20205. /** @hidden */
  20206. AbstractMesh.prototype._removeLightSource = function (light) {
  20207. var index = this._lightSources.indexOf(light);
  20208. if (index === -1) {
  20209. return;
  20210. }
  20211. this._lightSources.splice(index, 1);
  20212. this._markSubMeshesAsLightDirty();
  20213. };
  20214. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20215. if (!this.subMeshes) {
  20216. return;
  20217. }
  20218. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20219. var subMesh = _a[_i];
  20220. if (subMesh._materialDefines) {
  20221. func(subMesh._materialDefines);
  20222. }
  20223. }
  20224. };
  20225. /** @hidden */
  20226. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20227. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20228. };
  20229. /** @hidden */
  20230. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20231. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20232. };
  20233. /** @hidden */
  20234. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20235. if (!this.subMeshes) {
  20236. return;
  20237. }
  20238. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20239. var subMesh = _a[_i];
  20240. var material = subMesh.getMaterial();
  20241. if (material) {
  20242. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20243. }
  20244. }
  20245. };
  20246. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20247. /**
  20248. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20249. */
  20250. get: function () {
  20251. return this._scaling;
  20252. },
  20253. set: function (newScaling) {
  20254. this._scaling = newScaling;
  20255. if (this.physicsImpostor) {
  20256. this.physicsImpostor.forceUpdate();
  20257. }
  20258. },
  20259. enumerable: true,
  20260. configurable: true
  20261. });
  20262. // Methods
  20263. /**
  20264. * Disables the mesh edge rendering mode
  20265. * @returns the currentAbstractMesh
  20266. */
  20267. AbstractMesh.prototype.disableEdgesRendering = function () {
  20268. if (this._edgesRenderer) {
  20269. this._edgesRenderer.dispose();
  20270. this._edgesRenderer = null;
  20271. }
  20272. return this;
  20273. };
  20274. /**
  20275. * Enables the edge rendering mode on the mesh.
  20276. * This mode makes the mesh edges visible
  20277. * @param epsilon defines the maximal distance between two angles to detect a face
  20278. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20279. * @returns the currentAbstractMesh
  20280. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20281. */
  20282. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20283. if (epsilon === void 0) { epsilon = 0.95; }
  20284. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20285. this.disableEdgesRendering();
  20286. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20287. return this;
  20288. };
  20289. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20290. /**
  20291. * Gets the edgesRenderer associated with the mesh
  20292. */
  20293. get: function () {
  20294. return this._edgesRenderer;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20300. /**
  20301. * Returns true if the mesh is blocked. Implemented by child classes
  20302. */
  20303. get: function () {
  20304. return false;
  20305. },
  20306. enumerable: true,
  20307. configurable: true
  20308. });
  20309. /**
  20310. * Returns the mesh itself by default. Implemented by child classes
  20311. * @param camera defines the camera to use to pick the right LOD level
  20312. * @returns the currentAbstractMesh
  20313. */
  20314. AbstractMesh.prototype.getLOD = function (camera) {
  20315. return this;
  20316. };
  20317. /**
  20318. * Returns 0 by default. Implemented by child classes
  20319. * @returns an integer
  20320. */
  20321. AbstractMesh.prototype.getTotalVertices = function () {
  20322. return 0;
  20323. };
  20324. /**
  20325. * Returns null by default. Implemented by child classes
  20326. * @returns null
  20327. */
  20328. AbstractMesh.prototype.getIndices = function () {
  20329. return null;
  20330. };
  20331. /**
  20332. * Returns the array of the requested vertex data kind. Implemented by child classes
  20333. * @param kind defines the vertex data kind to use
  20334. * @returns null
  20335. */
  20336. AbstractMesh.prototype.getVerticesData = function (kind) {
  20337. return null;
  20338. };
  20339. /**
  20340. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20341. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20342. * Note that a new underlying VertexBuffer object is created each call.
  20343. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20344. * @param kind defines vertex data kind:
  20345. * * BABYLON.VertexBuffer.PositionKind
  20346. * * BABYLON.VertexBuffer.UVKind
  20347. * * BABYLON.VertexBuffer.UV2Kind
  20348. * * BABYLON.VertexBuffer.UV3Kind
  20349. * * BABYLON.VertexBuffer.UV4Kind
  20350. * * BABYLON.VertexBuffer.UV5Kind
  20351. * * BABYLON.VertexBuffer.UV6Kind
  20352. * * BABYLON.VertexBuffer.ColorKind
  20353. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20354. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20355. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20356. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20357. * @param data defines the data source
  20358. * @param updatable defines if the data must be flagged as updatable (or static)
  20359. * @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
  20360. * @returns the current mesh
  20361. */
  20362. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20363. return this;
  20364. };
  20365. /**
  20366. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20367. * If the mesh has no geometry, it is simply returned as it is.
  20368. * @param kind defines vertex data kind:
  20369. * * BABYLON.VertexBuffer.PositionKind
  20370. * * BABYLON.VertexBuffer.UVKind
  20371. * * BABYLON.VertexBuffer.UV2Kind
  20372. * * BABYLON.VertexBuffer.UV3Kind
  20373. * * BABYLON.VertexBuffer.UV4Kind
  20374. * * BABYLON.VertexBuffer.UV5Kind
  20375. * * BABYLON.VertexBuffer.UV6Kind
  20376. * * BABYLON.VertexBuffer.ColorKind
  20377. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20378. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20379. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20380. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20381. * @param data defines the data source
  20382. * @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
  20383. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20384. * @returns the current mesh
  20385. */
  20386. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20387. return this;
  20388. };
  20389. /**
  20390. * Sets the mesh indices,
  20391. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20392. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20393. * @param totalVertices Defines the total number of vertices
  20394. * @returns the current mesh
  20395. */
  20396. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20397. return this;
  20398. };
  20399. /**
  20400. * Gets a boolean indicating if specific vertex data is present
  20401. * @param kind defines the vertex data kind to use
  20402. * @returns true is data kind is present
  20403. */
  20404. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20405. return false;
  20406. };
  20407. /**
  20408. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20409. * @returns a BoundingInfo
  20410. */
  20411. AbstractMesh.prototype.getBoundingInfo = function () {
  20412. if (this._masterMesh) {
  20413. return this._masterMesh.getBoundingInfo();
  20414. }
  20415. if (!this._boundingInfo) {
  20416. // this._boundingInfo is being created here
  20417. this._updateBoundingInfo();
  20418. }
  20419. // cannot be null.
  20420. return this._boundingInfo;
  20421. };
  20422. /**
  20423. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20424. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20425. * @returns the current mesh
  20426. */
  20427. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20428. if (includeDescendants === void 0) { includeDescendants = true; }
  20429. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20430. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20431. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20432. if (maxDimension === 0) {
  20433. return this;
  20434. }
  20435. var scale = 1 / maxDimension;
  20436. this.scaling.scaleInPlace(scale);
  20437. return this;
  20438. };
  20439. /**
  20440. * Overwrite the current bounding info
  20441. * @param boundingInfo defines the new bounding info
  20442. * @returns the current mesh
  20443. */
  20444. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20445. this._boundingInfo = boundingInfo;
  20446. return this;
  20447. };
  20448. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20449. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20450. get: function () {
  20451. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20452. },
  20453. enumerable: true,
  20454. configurable: true
  20455. });
  20456. /** @hidden */
  20457. AbstractMesh.prototype._preActivate = function () {
  20458. };
  20459. /** @hidden */
  20460. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20461. };
  20462. /** @hidden */
  20463. AbstractMesh.prototype._activate = function (renderId) {
  20464. this._renderId = renderId;
  20465. };
  20466. /**
  20467. * Gets the current world matrix
  20468. * @returns a Matrix
  20469. */
  20470. AbstractMesh.prototype.getWorldMatrix = function () {
  20471. if (this._masterMesh) {
  20472. return this._masterMesh.getWorldMatrix();
  20473. }
  20474. return _super.prototype.getWorldMatrix.call(this);
  20475. };
  20476. /** @hidden */
  20477. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20478. if (this._masterMesh) {
  20479. return this._masterMesh._getWorldMatrixDeterminant();
  20480. }
  20481. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20482. };
  20483. // ================================== Point of View Movement =================================
  20484. /**
  20485. * Perform relative position change from the point of view of behind the front of the mesh.
  20486. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20487. * Supports definition of mesh facing forward or backward
  20488. * @param amountRight defines the distance on the right axis
  20489. * @param amountUp defines the distance on the up axis
  20490. * @param amountForward defines the distance on the forward axis
  20491. * @returns the current mesh
  20492. */
  20493. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20494. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20495. return this;
  20496. };
  20497. /**
  20498. * Calculate relative position change from the point of view of behind the front of the mesh.
  20499. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20500. * Supports definition of mesh facing forward or backward
  20501. * @param amountRight defines the distance on the right axis
  20502. * @param amountUp defines the distance on the up axis
  20503. * @param amountForward defines the distance on the forward axis
  20504. * @returns the new displacement vector
  20505. */
  20506. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20507. var rotMatrix = new BABYLON.Matrix();
  20508. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20509. rotQuaternion.toRotationMatrix(rotMatrix);
  20510. var translationDelta = BABYLON.Vector3.Zero();
  20511. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20513. return translationDelta;
  20514. };
  20515. // ================================== Point of View Rotation =================================
  20516. /**
  20517. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20518. * Supports definition of mesh facing forward or backward
  20519. * @param flipBack defines the flip
  20520. * @param twirlClockwise defines the twirl
  20521. * @param tiltRight defines the tilt
  20522. * @returns the current mesh
  20523. */
  20524. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20525. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20526. return this;
  20527. };
  20528. /**
  20529. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20530. * Supports definition of mesh facing forward or backward.
  20531. * @param flipBack defines the flip
  20532. * @param twirlClockwise defines the twirl
  20533. * @param tiltRight defines the tilt
  20534. * @returns the new rotation vector
  20535. */
  20536. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20537. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20538. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20539. };
  20540. /**
  20541. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20542. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20543. * @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
  20544. * @returns the new bounding vectors
  20545. */
  20546. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20547. if (includeDescendants === void 0) { includeDescendants = true; }
  20548. if (predicate === void 0) { predicate = null; }
  20549. // Ensures that all world matrix will be recomputed.
  20550. this.getScene().incrementRenderId();
  20551. this.computeWorldMatrix(true);
  20552. var min;
  20553. var max;
  20554. var boundingInfo = this.getBoundingInfo();
  20555. if (!this.subMeshes) {
  20556. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20557. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20558. }
  20559. else {
  20560. min = boundingInfo.boundingBox.minimumWorld;
  20561. max = boundingInfo.boundingBox.maximumWorld;
  20562. }
  20563. if (includeDescendants) {
  20564. var descendants = this.getDescendants(false);
  20565. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20566. var descendant = descendants_1[_i];
  20567. var childMesh = descendant;
  20568. childMesh.computeWorldMatrix(true);
  20569. // Filters meshes based on custom predicate function.
  20570. if (predicate && !predicate(childMesh)) {
  20571. continue;
  20572. }
  20573. //make sure we have the needed params to get mix and max
  20574. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20575. continue;
  20576. }
  20577. var childBoundingInfo = childMesh.getBoundingInfo();
  20578. var boundingBox = childBoundingInfo.boundingBox;
  20579. var minBox = boundingBox.minimumWorld;
  20580. var maxBox = boundingBox.maximumWorld;
  20581. BABYLON.Tools.CheckExtends(minBox, min, max);
  20582. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20583. }
  20584. }
  20585. return {
  20586. min: min,
  20587. max: max
  20588. };
  20589. };
  20590. /** @hidden */
  20591. AbstractMesh.prototype._updateBoundingInfo = function () {
  20592. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20593. this._boundingInfo.update(this.worldMatrixFromCache);
  20594. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20595. return this;
  20596. };
  20597. /** @hidden */
  20598. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20599. if (!this.subMeshes) {
  20600. return this;
  20601. }
  20602. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20603. var subMesh = this.subMeshes[subIndex];
  20604. if (!subMesh.IsGlobal) {
  20605. subMesh.updateBoundingInfo(matrix);
  20606. }
  20607. }
  20608. return this;
  20609. };
  20610. /** @hidden */
  20611. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20612. // Bounding info
  20613. this._updateBoundingInfo();
  20614. };
  20615. /**
  20616. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20617. * A mesh is in the frustum if its bounding box intersects the frustum
  20618. * @param frustumPlanes defines the frustum to test
  20619. * @returns true if the mesh is in the frustum planes
  20620. */
  20621. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20622. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20623. };
  20624. /**
  20625. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20626. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20627. * @param frustumPlanes defines the frustum to test
  20628. * @returns true if the mesh is completely in the frustum planes
  20629. */
  20630. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20631. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20632. };
  20633. /**
  20634. * True if the mesh intersects another mesh or a SolidParticle object
  20635. * @param mesh defines a target mesh or SolidParticle to test
  20636. * @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)
  20637. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20638. * @returns true if there is an intersection
  20639. */
  20640. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20641. if (precise === void 0) { precise = false; }
  20642. if (!this._boundingInfo || !mesh._boundingInfo) {
  20643. return false;
  20644. }
  20645. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20646. return true;
  20647. }
  20648. if (includeDescendants) {
  20649. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20650. var child = _a[_i];
  20651. if (child.intersectsMesh(mesh, precise, true)) {
  20652. return true;
  20653. }
  20654. }
  20655. }
  20656. return false;
  20657. };
  20658. /**
  20659. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20660. * @param point defines the point to test
  20661. * @returns true if there is an intersection
  20662. */
  20663. AbstractMesh.prototype.intersectsPoint = function (point) {
  20664. if (!this._boundingInfo) {
  20665. return false;
  20666. }
  20667. return this._boundingInfo.intersectsPoint(point);
  20668. };
  20669. /**
  20670. * Gets the current physics impostor
  20671. * @see http://doc.babylonjs.com/features/physics_engine
  20672. * @returns a physics impostor or null
  20673. */
  20674. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20675. return this.physicsImpostor;
  20676. };
  20677. /**
  20678. * Gets the position of the current mesh in camera space
  20679. * @param camera defines the camera to use
  20680. * @returns a position
  20681. */
  20682. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20683. if (camera === void 0) { camera = null; }
  20684. if (!camera) {
  20685. camera = this.getScene().activeCamera;
  20686. }
  20687. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20688. };
  20689. /**
  20690. * Returns the distance from the mesh to the active camera
  20691. * @param camera defines the camera to use
  20692. * @returns the distance
  20693. */
  20694. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20695. if (camera === void 0) { camera = null; }
  20696. if (!camera) {
  20697. camera = this.getScene().activeCamera;
  20698. }
  20699. return this.absolutePosition.subtract(camera.position).length();
  20700. };
  20701. /**
  20702. * Apply a physic impulse to the mesh
  20703. * @param force defines the force to apply
  20704. * @param contactPoint defines where to apply the force
  20705. * @returns the current mesh
  20706. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20707. */
  20708. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20709. if (!this.physicsImpostor) {
  20710. return this;
  20711. }
  20712. this.physicsImpostor.applyImpulse(force, contactPoint);
  20713. return this;
  20714. };
  20715. /**
  20716. * Creates a physic joint between two meshes
  20717. * @param otherMesh defines the other mesh to use
  20718. * @param pivot1 defines the pivot to use on this mesh
  20719. * @param pivot2 defines the pivot to use on the other mesh
  20720. * @param options defines additional options (can be plugin dependent)
  20721. * @returns the current mesh
  20722. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20723. */
  20724. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20725. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20726. return this;
  20727. }
  20728. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20729. mainPivot: pivot1,
  20730. connectedPivot: pivot2,
  20731. nativeParams: options
  20732. });
  20733. return this;
  20734. };
  20735. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20736. // Collisions
  20737. /**
  20738. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20739. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20740. */
  20741. get: function () {
  20742. return this._checkCollisions;
  20743. },
  20744. set: function (collisionEnabled) {
  20745. this._checkCollisions = collisionEnabled;
  20746. if (this.getScene().workerCollisions) {
  20747. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20748. }
  20749. },
  20750. enumerable: true,
  20751. configurable: true
  20752. });
  20753. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20754. /**
  20755. * Gets Collider object used to compute collisions (not physics)
  20756. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20757. */
  20758. get: function () {
  20759. return this._collider;
  20760. },
  20761. enumerable: true,
  20762. configurable: true
  20763. });
  20764. /**
  20765. * Move the mesh using collision engine
  20766. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20767. * @param displacement defines the requested displacement vector
  20768. * @returns the current mesh
  20769. */
  20770. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20771. var globalPosition = this.getAbsolutePosition();
  20772. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20773. if (!this._collider) {
  20774. this._collider = new BABYLON.Collider();
  20775. }
  20776. this._collider._radius = this.ellipsoid;
  20777. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20778. return this;
  20779. };
  20780. // Submeshes octree
  20781. /**
  20782. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20783. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20784. * @param maxCapacity defines the maximum size of each block (64 by default)
  20785. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20786. * @returns the new octree
  20787. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20788. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20789. */
  20790. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20791. if (maxCapacity === void 0) { maxCapacity = 64; }
  20792. if (maxDepth === void 0) { maxDepth = 2; }
  20793. if (!this._submeshesOctree) {
  20794. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20795. }
  20796. this.computeWorldMatrix(true);
  20797. var boundingInfo = this.getBoundingInfo();
  20798. // Update octree
  20799. var bbox = boundingInfo.boundingBox;
  20800. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20801. return this._submeshesOctree;
  20802. };
  20803. // Collisions
  20804. /** @hidden */
  20805. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20806. this._generatePointsArray();
  20807. if (!this._positions) {
  20808. return this;
  20809. }
  20810. // Transformation
  20811. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20812. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20813. subMesh._lastColliderWorldVertices = [];
  20814. subMesh._trianglePlanes = [];
  20815. var start = subMesh.verticesStart;
  20816. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20817. for (var i = start; i < end; i++) {
  20818. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20819. }
  20820. }
  20821. // Collide
  20822. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20823. if (collider.collisionFound) {
  20824. collider.collidedMesh = this;
  20825. }
  20826. return this;
  20827. };
  20828. /** @hidden */
  20829. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20830. var subMeshes;
  20831. var len;
  20832. // Octrees
  20833. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20834. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20835. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20836. len = intersections.length;
  20837. subMeshes = intersections.data;
  20838. }
  20839. else {
  20840. subMeshes = this.subMeshes;
  20841. len = subMeshes.length;
  20842. }
  20843. for (var index = 0; index < len; index++) {
  20844. var subMesh = subMeshes[index];
  20845. // Bounding test
  20846. if (len > 1 && !subMesh._checkCollision(collider))
  20847. continue;
  20848. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20849. }
  20850. return this;
  20851. };
  20852. /** @hidden */
  20853. AbstractMesh.prototype._checkCollision = function (collider) {
  20854. // Bounding box test
  20855. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20856. return this;
  20857. // Transformation matrix
  20858. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20859. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20860. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20861. return this;
  20862. };
  20863. // Picking
  20864. /** @hidden */
  20865. AbstractMesh.prototype._generatePointsArray = function () {
  20866. return false;
  20867. };
  20868. /**
  20869. * Checks if the passed Ray intersects with the mesh
  20870. * @param ray defines the ray to use
  20871. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20872. * @returns the picking info
  20873. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20874. */
  20875. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20876. var pickingInfo = new BABYLON.PickingInfo();
  20877. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20878. return pickingInfo;
  20879. }
  20880. if (!this._generatePointsArray()) {
  20881. return pickingInfo;
  20882. }
  20883. var intersectInfo = null;
  20884. // Octrees
  20885. var subMeshes;
  20886. var len;
  20887. if (this._submeshesOctree && this.useOctreeForPicking) {
  20888. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20889. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20890. len = intersections.length;
  20891. subMeshes = intersections.data;
  20892. }
  20893. else {
  20894. subMeshes = this.subMeshes;
  20895. len = subMeshes.length;
  20896. }
  20897. for (var index = 0; index < len; index++) {
  20898. var subMesh = subMeshes[index];
  20899. // Bounding test
  20900. if (len > 1 && !subMesh.canIntersects(ray))
  20901. continue;
  20902. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20903. if (currentIntersectInfo) {
  20904. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20905. intersectInfo = currentIntersectInfo;
  20906. intersectInfo.subMeshId = index;
  20907. if (fastCheck) {
  20908. break;
  20909. }
  20910. }
  20911. }
  20912. }
  20913. if (intersectInfo) {
  20914. // Get picked point
  20915. var world = this.getWorldMatrix();
  20916. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20917. var direction = ray.direction.clone();
  20918. direction = direction.scale(intersectInfo.distance);
  20919. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20920. var pickedPoint = worldOrigin.add(worldDirection);
  20921. // Return result
  20922. pickingInfo.hit = true;
  20923. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20924. pickingInfo.pickedPoint = pickedPoint;
  20925. pickingInfo.pickedMesh = this;
  20926. pickingInfo.bu = intersectInfo.bu || 0;
  20927. pickingInfo.bv = intersectInfo.bv || 0;
  20928. pickingInfo.faceId = intersectInfo.faceId;
  20929. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20930. return pickingInfo;
  20931. }
  20932. return pickingInfo;
  20933. };
  20934. /**
  20935. * Clones the current mesh
  20936. * @param name defines the mesh name
  20937. * @param newParent defines the new mesh parent
  20938. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20939. * @returns the new mesh
  20940. */
  20941. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20942. return null;
  20943. };
  20944. /**
  20945. * Disposes all the submeshes of the current meshnp
  20946. * @returns the current mesh
  20947. */
  20948. AbstractMesh.prototype.releaseSubMeshes = function () {
  20949. if (this.subMeshes) {
  20950. while (this.subMeshes.length) {
  20951. this.subMeshes[0].dispose();
  20952. }
  20953. }
  20954. else {
  20955. this.subMeshes = new Array();
  20956. }
  20957. return this;
  20958. };
  20959. /**
  20960. * Releases resources associated with this abstract mesh.
  20961. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20962. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20963. */
  20964. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20965. var _this = this;
  20966. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20967. var index;
  20968. // Smart Array Retainers.
  20969. this.getScene().freeActiveMeshes();
  20970. this.getScene().freeRenderingGroups();
  20971. // Action manager
  20972. if (this.actionManager !== undefined && this.actionManager !== null) {
  20973. this.actionManager.dispose();
  20974. this.actionManager = null;
  20975. }
  20976. // Skeleton
  20977. this._skeleton = null;
  20978. // Physics
  20979. if (this.physicsImpostor) {
  20980. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20981. }
  20982. // Intersections in progress
  20983. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20984. var other = this._intersectionsInProgress[index];
  20985. var pos = other._intersectionsInProgress.indexOf(this);
  20986. other._intersectionsInProgress.splice(pos, 1);
  20987. }
  20988. this._intersectionsInProgress = [];
  20989. // Lights
  20990. var lights = this.getScene().lights;
  20991. lights.forEach(function (light) {
  20992. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20993. if (meshIndex !== -1) {
  20994. light.includedOnlyMeshes.splice(meshIndex, 1);
  20995. }
  20996. meshIndex = light.excludedMeshes.indexOf(_this);
  20997. if (meshIndex !== -1) {
  20998. light.excludedMeshes.splice(meshIndex, 1);
  20999. }
  21000. // Shadow generators
  21001. var generator = light.getShadowGenerator();
  21002. if (generator) {
  21003. var shadowMap = generator.getShadowMap();
  21004. if (shadowMap && shadowMap.renderList) {
  21005. meshIndex = shadowMap.renderList.indexOf(_this);
  21006. if (meshIndex !== -1) {
  21007. shadowMap.renderList.splice(meshIndex, 1);
  21008. }
  21009. }
  21010. }
  21011. });
  21012. // Edges
  21013. if (this._edgesRenderer) {
  21014. this._edgesRenderer.dispose();
  21015. this._edgesRenderer = null;
  21016. }
  21017. // SubMeshes
  21018. if (this.getClassName() !== "InstancedMesh") {
  21019. this.releaseSubMeshes();
  21020. }
  21021. // Octree
  21022. var sceneOctree = this.getScene().selectionOctree;
  21023. if (sceneOctree !== undefined && sceneOctree !== null) {
  21024. var index = sceneOctree.dynamicContent.indexOf(this);
  21025. if (index !== -1) {
  21026. sceneOctree.dynamicContent.splice(index, 1);
  21027. }
  21028. }
  21029. // Query
  21030. var engine = this.getScene().getEngine();
  21031. if (this._occlusionQuery) {
  21032. this._isOcclusionQueryInProgress = false;
  21033. engine.deleteQuery(this._occlusionQuery);
  21034. this._occlusionQuery = null;
  21035. }
  21036. // Engine
  21037. engine.wipeCaches();
  21038. // Remove from scene
  21039. this.getScene().removeMesh(this);
  21040. if (disposeMaterialAndTextures) {
  21041. if (this.material) {
  21042. this.material.dispose(false, true);
  21043. }
  21044. }
  21045. if (!doNotRecurse) {
  21046. // Particles
  21047. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21048. if (this.getScene().particleSystems[index].emitter === this) {
  21049. this.getScene().particleSystems[index].dispose();
  21050. index--;
  21051. }
  21052. }
  21053. }
  21054. // facet data
  21055. if (this._facetDataEnabled) {
  21056. this.disableFacetData();
  21057. }
  21058. this.onAfterWorldMatrixUpdateObservable.clear();
  21059. this.onCollideObservable.clear();
  21060. this.onCollisionPositionChangeObservable.clear();
  21061. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21062. };
  21063. /**
  21064. * Adds the passed mesh as a child to the current mesh
  21065. * @param mesh defines the child mesh
  21066. * @returns the current mesh
  21067. */
  21068. AbstractMesh.prototype.addChild = function (mesh) {
  21069. mesh.setParent(this);
  21070. return this;
  21071. };
  21072. /**
  21073. * Removes the passed mesh from the current mesh children list
  21074. * @param mesh defines the child mesh
  21075. * @returns the current mesh
  21076. */
  21077. AbstractMesh.prototype.removeChild = function (mesh) {
  21078. mesh.setParent(null);
  21079. return this;
  21080. };
  21081. // Facet data
  21082. /** @hidden */
  21083. AbstractMesh.prototype._initFacetData = function () {
  21084. if (!this._facetNormals) {
  21085. this._facetNormals = new Array();
  21086. }
  21087. if (!this._facetPositions) {
  21088. this._facetPositions = new Array();
  21089. }
  21090. if (!this._facetPartitioning) {
  21091. this._facetPartitioning = new Array();
  21092. }
  21093. this._facetNb = (this.getIndices().length / 3) | 0;
  21094. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21095. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21096. for (var f = 0; f < this._facetNb; f++) {
  21097. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21098. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21099. }
  21100. this._facetDataEnabled = true;
  21101. return this;
  21102. };
  21103. /**
  21104. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21105. * This method can be called within the render loop.
  21106. * 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
  21107. * @returns the current mesh
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.updateFacetData = function () {
  21111. if (!this._facetDataEnabled) {
  21112. this._initFacetData();
  21113. }
  21114. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21115. var indices = this.getIndices();
  21116. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21117. var bInfo = this.getBoundingInfo();
  21118. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21119. // init arrays, matrix and sort function on first call
  21120. this._facetDepthSortEnabled = true;
  21121. if (indices instanceof Uint16Array) {
  21122. this._depthSortedIndices = new Uint16Array(indices);
  21123. }
  21124. else if (indices instanceof Uint32Array) {
  21125. this._depthSortedIndices = new Uint32Array(indices);
  21126. }
  21127. else {
  21128. var needs32bits = false;
  21129. for (var i = 0; i < indices.length; i++) {
  21130. if (indices[i] > 65535) {
  21131. needs32bits = true;
  21132. break;
  21133. }
  21134. }
  21135. if (needs32bits) {
  21136. this._depthSortedIndices = new Uint32Array(indices);
  21137. }
  21138. else {
  21139. this._depthSortedIndices = new Uint16Array(indices);
  21140. }
  21141. }
  21142. this._facetDepthSortFunction = function (f1, f2) {
  21143. return (f2.sqDistance - f1.sqDistance);
  21144. };
  21145. if (!this._facetDepthSortFrom) {
  21146. var camera = this.getScene().activeCamera;
  21147. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21148. }
  21149. this._depthSortedFacets = [];
  21150. for (var f = 0; f < this._facetNb; f++) {
  21151. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21152. this._depthSortedFacets.push(depthSortedFacet);
  21153. }
  21154. this._invertedMatrix = BABYLON.Matrix.Identity();
  21155. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21156. }
  21157. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21158. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21159. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21160. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21161. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21162. this._subDiv.max = this._partitioningSubdivisions;
  21163. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21164. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21165. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21166. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21167. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21168. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21169. // set the parameters for ComputeNormals()
  21170. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21171. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21172. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21173. this._facetParameters.bInfo = bInfo;
  21174. this._facetParameters.bbSize = this._bbSize;
  21175. this._facetParameters.subDiv = this._subDiv;
  21176. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21177. this._facetParameters.depthSort = this._facetDepthSort;
  21178. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21179. this.computeWorldMatrix(true);
  21180. this._worldMatrix.invertToRef(this._invertedMatrix);
  21181. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21182. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21183. }
  21184. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21185. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21186. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21187. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21188. var l = (this._depthSortedIndices.length / 3) | 0;
  21189. for (var f = 0; f < l; f++) {
  21190. var sind = this._depthSortedFacets[f].ind;
  21191. this._depthSortedIndices[f * 3] = indices[sind];
  21192. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21193. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21194. }
  21195. this.updateIndices(this._depthSortedIndices);
  21196. }
  21197. return this;
  21198. };
  21199. /**
  21200. * Returns the facetLocalNormals array.
  21201. * The normals are expressed in the mesh local spac
  21202. * @returns an array of Vector3
  21203. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21204. */
  21205. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21206. if (!this._facetNormals) {
  21207. this.updateFacetData();
  21208. }
  21209. return this._facetNormals;
  21210. };
  21211. /**
  21212. * Returns the facetLocalPositions array.
  21213. * The facet positions are expressed in the mesh local space
  21214. * @returns an array of Vector3
  21215. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21216. */
  21217. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21218. if (!this._facetPositions) {
  21219. this.updateFacetData();
  21220. }
  21221. return this._facetPositions;
  21222. };
  21223. /**
  21224. * Returns the facetLocalPartioning array
  21225. * @returns an array of array of numbers
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21229. if (!this._facetPartitioning) {
  21230. this.updateFacetData();
  21231. }
  21232. return this._facetPartitioning;
  21233. };
  21234. /**
  21235. * Returns the i-th facet position in the world system.
  21236. * This method allocates a new Vector3 per call
  21237. * @param i defines the facet index
  21238. * @returns a new Vector3
  21239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21240. */
  21241. AbstractMesh.prototype.getFacetPosition = function (i) {
  21242. var pos = BABYLON.Vector3.Zero();
  21243. this.getFacetPositionToRef(i, pos);
  21244. return pos;
  21245. };
  21246. /**
  21247. * Sets the reference Vector3 with the i-th facet position in the world system
  21248. * @param i defines the facet index
  21249. * @param ref defines the target vector
  21250. * @returns the current mesh
  21251. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21252. */
  21253. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21254. var localPos = (this.getFacetLocalPositions())[i];
  21255. var world = this.getWorldMatrix();
  21256. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21257. return this;
  21258. };
  21259. /**
  21260. * Returns the i-th facet normal in the world system.
  21261. * This method allocates a new Vector3 per call
  21262. * @param i defines the facet index
  21263. * @returns a new Vector3
  21264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21265. */
  21266. AbstractMesh.prototype.getFacetNormal = function (i) {
  21267. var norm = BABYLON.Vector3.Zero();
  21268. this.getFacetNormalToRef(i, norm);
  21269. return norm;
  21270. };
  21271. /**
  21272. * Sets the reference Vector3 with the i-th facet normal in the world system
  21273. * @param i defines the facet index
  21274. * @param ref defines the target vector
  21275. * @returns the current mesh
  21276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21277. */
  21278. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21279. var localNorm = (this.getFacetLocalNormals())[i];
  21280. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21281. return this;
  21282. };
  21283. /**
  21284. * 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)
  21285. * @param x defines x coordinate
  21286. * @param y defines y coordinate
  21287. * @param z defines z coordinate
  21288. * @returns the array of facet indexes
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21292. var bInfo = this.getBoundingInfo();
  21293. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21294. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21295. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21296. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21297. return null;
  21298. }
  21299. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21300. };
  21301. /**
  21302. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21303. * @param projected sets as the (x,y,z) world projection on the facet
  21304. * @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
  21305. * @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
  21306. * @param x defines x coordinate
  21307. * @param y defines y coordinate
  21308. * @param z defines z coordinate
  21309. * @returns the face index if found (or null instead)
  21310. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21311. */
  21312. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21313. if (checkFace === void 0) { checkFace = false; }
  21314. if (facing === void 0) { facing = true; }
  21315. var world = this.getWorldMatrix();
  21316. var invMat = BABYLON.Tmp.Matrix[5];
  21317. world.invertToRef(invMat);
  21318. var invVect = BABYLON.Tmp.Vector3[8];
  21319. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21320. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21321. if (projected) {
  21322. // tranform the local computed projected vector to world coordinates
  21323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21324. }
  21325. return closest;
  21326. };
  21327. /**
  21328. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21329. * @param projected sets as the (x,y,z) local projection on the facet
  21330. * @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
  21331. * @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
  21332. * @param x defines x coordinate
  21333. * @param y defines y coordinate
  21334. * @param z defines z coordinate
  21335. * @returns the face index if found (or null instead)
  21336. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21337. */
  21338. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21339. if (checkFace === void 0) { checkFace = false; }
  21340. if (facing === void 0) { facing = true; }
  21341. var closest = null;
  21342. var tmpx = 0.0;
  21343. var tmpy = 0.0;
  21344. var tmpz = 0.0;
  21345. var d = 0.0; // tmp dot facet normal * facet position
  21346. var t0 = 0.0;
  21347. var projx = 0.0;
  21348. var projy = 0.0;
  21349. var projz = 0.0;
  21350. // Get all the facets in the same partitioning block than (x, y, z)
  21351. var facetPositions = this.getFacetLocalPositions();
  21352. var facetNormals = this.getFacetLocalNormals();
  21353. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21354. if (!facetsInBlock) {
  21355. return null;
  21356. }
  21357. // Get the closest facet to (x, y, z)
  21358. var shortest = Number.MAX_VALUE; // init distance vars
  21359. var tmpDistance = shortest;
  21360. var fib; // current facet in the block
  21361. var norm; // current facet normal
  21362. var p0; // current facet barycenter position
  21363. // loop on all the facets in the current partitioning block
  21364. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21365. fib = facetsInBlock[idx];
  21366. norm = facetNormals[fib];
  21367. p0 = facetPositions[fib];
  21368. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21369. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21370. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21371. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21372. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21373. projx = x + norm.x * t0;
  21374. projy = y + norm.y * t0;
  21375. projz = z + norm.z * t0;
  21376. tmpx = projx - x;
  21377. tmpy = projy - y;
  21378. tmpz = projz - z;
  21379. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21380. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21381. shortest = tmpDistance;
  21382. closest = fib;
  21383. if (projected) {
  21384. projected.x = projx;
  21385. projected.y = projy;
  21386. projected.z = projz;
  21387. }
  21388. }
  21389. }
  21390. }
  21391. return closest;
  21392. };
  21393. /**
  21394. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21395. * @returns the parameters
  21396. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21397. */
  21398. AbstractMesh.prototype.getFacetDataParameters = function () {
  21399. return this._facetParameters;
  21400. };
  21401. /**
  21402. * Disables the feature FacetData and frees the related memory
  21403. * @returns the current mesh
  21404. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21405. */
  21406. AbstractMesh.prototype.disableFacetData = function () {
  21407. if (this._facetDataEnabled) {
  21408. this._facetDataEnabled = false;
  21409. this._facetPositions = new Array();
  21410. this._facetNormals = new Array();
  21411. this._facetPartitioning = new Array();
  21412. this._facetParameters = null;
  21413. this._depthSortedIndices = new Uint32Array(0);
  21414. }
  21415. return this;
  21416. };
  21417. /**
  21418. * Updates the AbstractMesh indices array
  21419. * @param indices defines the data source
  21420. * @returns the current mesh
  21421. */
  21422. AbstractMesh.prototype.updateIndices = function (indices) {
  21423. return this;
  21424. };
  21425. /**
  21426. * Creates new normals data for the mesh
  21427. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21428. * @returns the current mesh
  21429. */
  21430. AbstractMesh.prototype.createNormals = function (updatable) {
  21431. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21432. var indices = this.getIndices();
  21433. var normals;
  21434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21435. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21436. }
  21437. else {
  21438. normals = [];
  21439. }
  21440. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21442. return this;
  21443. };
  21444. /**
  21445. * Align the mesh with a normal
  21446. * @param normal defines the normal to use
  21447. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21448. * @returns the current mesh
  21449. */
  21450. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21451. if (!upDirection) {
  21452. upDirection = BABYLON.Axis.Y;
  21453. }
  21454. var axisX = BABYLON.Tmp.Vector3[0];
  21455. var axisZ = BABYLON.Tmp.Vector3[1];
  21456. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21457. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21458. if (this.rotationQuaternion) {
  21459. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21460. }
  21461. else {
  21462. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21463. }
  21464. return this;
  21465. };
  21466. /** @hidden */
  21467. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21468. var engine = this.getEngine();
  21469. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21470. this._isOccluded = false;
  21471. return;
  21472. }
  21473. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21474. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21475. if (isOcclusionQueryAvailable) {
  21476. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21477. this._isOcclusionQueryInProgress = false;
  21478. this._occlusionInternalRetryCounter = 0;
  21479. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21480. }
  21481. else {
  21482. this._occlusionInternalRetryCounter++;
  21483. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21484. this._isOcclusionQueryInProgress = false;
  21485. this._occlusionInternalRetryCounter = 0;
  21486. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21487. // if strict continue the last state of the object.
  21488. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21489. }
  21490. else {
  21491. return;
  21492. }
  21493. }
  21494. }
  21495. var scene = this.getScene();
  21496. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21497. if (!this._occlusionQuery) {
  21498. this._occlusionQuery = engine.createQuery();
  21499. }
  21500. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21501. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21502. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21503. this._isOcclusionQueryInProgress = true;
  21504. };
  21505. /** No occlusion */
  21506. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21507. /** Occlusion set to optimisitic */
  21508. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21509. /** Occlusion set to strict */
  21510. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21511. /** Use an accurante occlusion algorithm */
  21512. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21513. /** Use a conservative occlusion algorithm */
  21514. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21515. return AbstractMesh;
  21516. }(BABYLON.TransformNode));
  21517. BABYLON.AbstractMesh = AbstractMesh;
  21518. })(BABYLON || (BABYLON = {}));
  21519. //# sourceMappingURL=babylon.abstractMesh.js.map
  21520. var BABYLON;
  21521. (function (BABYLON) {
  21522. /**
  21523. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21524. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21525. * 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.
  21526. */
  21527. var Light = /** @class */ (function (_super) {
  21528. __extends(Light, _super);
  21529. /**
  21530. * Creates a Light object in the scene.
  21531. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21532. * @param name The firendly name of the light
  21533. * @param scene The scene the light belongs too
  21534. */
  21535. function Light(name, scene) {
  21536. var _this = _super.call(this, name, scene) || this;
  21537. /**
  21538. * Diffuse gives the basic color to an object.
  21539. */
  21540. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21541. /**
  21542. * Specular produces a highlight color on an object.
  21543. * Note: This is note affecting PBR materials.
  21544. */
  21545. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21546. /**
  21547. * Strength of the light.
  21548. * Note: By default it is define in the framework own unit.
  21549. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21550. */
  21551. _this.intensity = 1.0;
  21552. /**
  21553. * Defines how far from the source the light is impacting in scene units.
  21554. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21555. */
  21556. _this.range = Number.MAX_VALUE;
  21557. /**
  21558. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21559. * of light.
  21560. */
  21561. _this._photometricScale = 1.0;
  21562. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21563. _this._radius = 0.00001;
  21564. /**
  21565. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21566. * exceeding the number allowed of the materials.
  21567. */
  21568. _this.renderPriority = 0;
  21569. _this._shadowEnabled = true;
  21570. _this._excludeWithLayerMask = 0;
  21571. _this._includeOnlyWithLayerMask = 0;
  21572. _this._lightmapMode = 0;
  21573. /**
  21574. * @hidden Internal use only.
  21575. */
  21576. _this._excludedMeshesIds = new Array();
  21577. /**
  21578. * @hidden Internal use only.
  21579. */
  21580. _this._includedOnlyMeshesIds = new Array();
  21581. _this.getScene().addLight(_this);
  21582. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21583. _this._buildUniformLayout();
  21584. _this.includedOnlyMeshes = new Array();
  21585. _this.excludedMeshes = new Array();
  21586. _this._resyncMeshes();
  21587. return _this;
  21588. }
  21589. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21590. /**
  21591. * If every light affecting the material is in this lightmapMode,
  21592. * material.lightmapTexture adds or multiplies
  21593. * (depends on material.useLightmapAsShadowmap)
  21594. * after every other light calculations.
  21595. */
  21596. get: function () {
  21597. return Light._LIGHTMAP_DEFAULT;
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21603. /**
  21604. * material.lightmapTexture as only diffuse lighting from this light
  21605. * adds only specular lighting from this light
  21606. * adds dynamic shadows
  21607. */
  21608. get: function () {
  21609. return Light._LIGHTMAP_SPECULAR;
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21615. /**
  21616. * material.lightmapTexture as only lighting
  21617. * no light calculation from this light
  21618. * only adds dynamic shadows from this light
  21619. */
  21620. get: function () {
  21621. return Light._LIGHTMAP_SHADOWSONLY;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21627. /**
  21628. * Each light type uses the default quantity according to its type:
  21629. * point/spot lights use luminous intensity
  21630. * directional lights use illuminance
  21631. */
  21632. get: function () {
  21633. return Light._INTENSITYMODE_AUTOMATIC;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21639. /**
  21640. * lumen (lm)
  21641. */
  21642. get: function () {
  21643. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21649. /**
  21650. * candela (lm/sr)
  21651. */
  21652. get: function () {
  21653. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21659. /**
  21660. * lux (lm/m^2)
  21661. */
  21662. get: function () {
  21663. return Light._INTENSITYMODE_ILLUMINANCE;
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21669. /**
  21670. * nit (cd/m^2)
  21671. */
  21672. get: function () {
  21673. return Light._INTENSITYMODE_LUMINANCE;
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21679. /**
  21680. * Light type const id of the point light.
  21681. */
  21682. get: function () {
  21683. return Light._LIGHTTYPEID_POINTLIGHT;
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21689. /**
  21690. * Light type const id of the directional light.
  21691. */
  21692. get: function () {
  21693. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21694. },
  21695. enumerable: true,
  21696. configurable: true
  21697. });
  21698. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21699. /**
  21700. * Light type const id of the spot light.
  21701. */
  21702. get: function () {
  21703. return Light._LIGHTTYPEID_SPOTLIGHT;
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21709. /**
  21710. * Light type const id of the hemispheric light.
  21711. */
  21712. get: function () {
  21713. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Object.defineProperty(Light.prototype, "intensityMode", {
  21719. /**
  21720. * Gets the photometric scale used to interpret the intensity.
  21721. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21722. */
  21723. get: function () {
  21724. return this._intensityMode;
  21725. },
  21726. /**
  21727. * Sets the photometric scale used to interpret the intensity.
  21728. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21729. */
  21730. set: function (value) {
  21731. this._intensityMode = value;
  21732. this._computePhotometricScale();
  21733. },
  21734. enumerable: true,
  21735. configurable: true
  21736. });
  21737. ;
  21738. ;
  21739. Object.defineProperty(Light.prototype, "radius", {
  21740. /**
  21741. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21742. */
  21743. get: function () {
  21744. return this._radius;
  21745. },
  21746. /**
  21747. * sets the light radius used by PBR Materials to simulate soft area lights.
  21748. */
  21749. set: function (value) {
  21750. this._radius = value;
  21751. this._computePhotometricScale();
  21752. },
  21753. enumerable: true,
  21754. configurable: true
  21755. });
  21756. ;
  21757. ;
  21758. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21759. /**
  21760. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21761. * the current shadow generator.
  21762. */
  21763. get: function () {
  21764. return this._shadowEnabled;
  21765. },
  21766. /**
  21767. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21768. * the current shadow generator.
  21769. */
  21770. set: function (value) {
  21771. if (this._shadowEnabled === value) {
  21772. return;
  21773. }
  21774. this._shadowEnabled = value;
  21775. this._markMeshesAsLightDirty();
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21781. /**
  21782. * Gets the only meshes impacted by this light.
  21783. */
  21784. get: function () {
  21785. return this._includedOnlyMeshes;
  21786. },
  21787. /**
  21788. * Sets the only meshes impacted by this light.
  21789. */
  21790. set: function (value) {
  21791. this._includedOnlyMeshes = value;
  21792. this._hookArrayForIncludedOnly(value);
  21793. },
  21794. enumerable: true,
  21795. configurable: true
  21796. });
  21797. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21798. /**
  21799. * Gets the meshes not impacted by this light.
  21800. */
  21801. get: function () {
  21802. return this._excludedMeshes;
  21803. },
  21804. /**
  21805. * Sets the meshes not impacted by this light.
  21806. */
  21807. set: function (value) {
  21808. this._excludedMeshes = value;
  21809. this._hookArrayForExcluded(value);
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21815. /**
  21816. * Gets the layer id use to find what meshes are not impacted by the light.
  21817. * Inactive if 0
  21818. */
  21819. get: function () {
  21820. return this._excludeWithLayerMask;
  21821. },
  21822. /**
  21823. * Sets the layer id use to find what meshes are not impacted by the light.
  21824. * Inactive if 0
  21825. */
  21826. set: function (value) {
  21827. this._excludeWithLayerMask = value;
  21828. this._resyncMeshes();
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21834. /**
  21835. * Gets the layer id use to find what meshes are impacted by the light.
  21836. * Inactive if 0
  21837. */
  21838. get: function () {
  21839. return this._includeOnlyWithLayerMask;
  21840. },
  21841. /**
  21842. * Sets the layer id use to find what meshes are impacted by the light.
  21843. * Inactive if 0
  21844. */
  21845. set: function (value) {
  21846. this._includeOnlyWithLayerMask = value;
  21847. this._resyncMeshes();
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(Light.prototype, "lightmapMode", {
  21853. /**
  21854. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21855. */
  21856. get: function () {
  21857. return this._lightmapMode;
  21858. },
  21859. /**
  21860. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21861. */
  21862. set: function (value) {
  21863. if (this._lightmapMode === value) {
  21864. return;
  21865. }
  21866. this._lightmapMode = value;
  21867. this._markMeshesAsLightDirty();
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. /**
  21873. * Returns the string "Light".
  21874. * @returns the class name
  21875. */
  21876. Light.prototype.getClassName = function () {
  21877. return "Light";
  21878. };
  21879. /**
  21880. * Converts the light information to a readable string for debug purpose.
  21881. * @param fullDetails Supports for multiple levels of logging within scene loading
  21882. * @returns the human readable light info
  21883. */
  21884. Light.prototype.toString = function (fullDetails) {
  21885. var ret = "Name: " + this.name;
  21886. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21887. if (this.animations) {
  21888. for (var i = 0; i < this.animations.length; i++) {
  21889. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21890. }
  21891. }
  21892. if (fullDetails) {
  21893. }
  21894. return ret;
  21895. };
  21896. /**
  21897. * Set the enabled state of this node.
  21898. * @param value - the new enabled state
  21899. */
  21900. Light.prototype.setEnabled = function (value) {
  21901. _super.prototype.setEnabled.call(this, value);
  21902. this._resyncMeshes();
  21903. };
  21904. /**
  21905. * Returns the Light associated shadow generator if any.
  21906. * @return the associated shadow generator.
  21907. */
  21908. Light.prototype.getShadowGenerator = function () {
  21909. return this._shadowGenerator;
  21910. };
  21911. /**
  21912. * Returns a Vector3, the absolute light position in the World.
  21913. * @returns the world space position of the light
  21914. */
  21915. Light.prototype.getAbsolutePosition = function () {
  21916. return BABYLON.Vector3.Zero();
  21917. };
  21918. /**
  21919. * Specifies if the light will affect the passed mesh.
  21920. * @param mesh The mesh to test against the light
  21921. * @return true the mesh is affected otherwise, false.
  21922. */
  21923. Light.prototype.canAffectMesh = function (mesh) {
  21924. if (!mesh) {
  21925. return true;
  21926. }
  21927. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21928. return false;
  21929. }
  21930. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21931. return false;
  21932. }
  21933. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21934. return false;
  21935. }
  21936. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21937. return false;
  21938. }
  21939. return true;
  21940. };
  21941. /**
  21942. * Computes and Returns the light World matrix.
  21943. * @returns the world matrix
  21944. */
  21945. Light.prototype.getWorldMatrix = function () {
  21946. this._currentRenderId = this.getScene().getRenderId();
  21947. this._childRenderId = this._currentRenderId;
  21948. var worldMatrix = this._getWorldMatrix();
  21949. if (this.parent && this.parent.getWorldMatrix) {
  21950. if (!this._parentedWorldMatrix) {
  21951. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21952. }
  21953. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21954. this._markSyncedWithParent();
  21955. return this._parentedWorldMatrix;
  21956. }
  21957. return worldMatrix;
  21958. };
  21959. /**
  21960. * Sort function to order lights for rendering.
  21961. * @param a First Light object to compare to second.
  21962. * @param b Second Light object to compare first.
  21963. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21964. */
  21965. Light.CompareLightsPriority = function (a, b) {
  21966. //shadow-casting lights have priority over non-shadow-casting lights
  21967. //the renderPrioirty is a secondary sort criterion
  21968. if (a.shadowEnabled !== b.shadowEnabled) {
  21969. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21970. }
  21971. return b.renderPriority - a.renderPriority;
  21972. };
  21973. /**
  21974. * Releases resources associated with this node.
  21975. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21976. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21977. */
  21978. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21979. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21980. if (this._shadowGenerator) {
  21981. this._shadowGenerator.dispose();
  21982. this._shadowGenerator = null;
  21983. }
  21984. // Animations
  21985. this.getScene().stopAnimation(this);
  21986. // Remove from meshes
  21987. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21988. var mesh = _a[_i];
  21989. mesh._removeLightSource(this);
  21990. }
  21991. this._uniformBuffer.dispose();
  21992. // Remove from scene
  21993. this.getScene().removeLight(this);
  21994. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21995. };
  21996. /**
  21997. * Returns the light type ID (integer).
  21998. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21999. */
  22000. Light.prototype.getTypeID = function () {
  22001. return 0;
  22002. };
  22003. /**
  22004. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22005. * @returns the scaled intensity in intensity mode unit
  22006. */
  22007. Light.prototype.getScaledIntensity = function () {
  22008. return this._photometricScale * this.intensity;
  22009. };
  22010. /**
  22011. * Returns a new Light object, named "name", from the current one.
  22012. * @param name The name of the cloned light
  22013. * @returns the new created light
  22014. */
  22015. Light.prototype.clone = function (name) {
  22016. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22017. if (!constructor) {
  22018. return null;
  22019. }
  22020. return BABYLON.SerializationHelper.Clone(constructor, this);
  22021. };
  22022. /**
  22023. * Serializes the current light into a Serialization object.
  22024. * @returns the serialized object.
  22025. */
  22026. Light.prototype.serialize = function () {
  22027. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22028. // Type
  22029. serializationObject.type = this.getTypeID();
  22030. // Parent
  22031. if (this.parent) {
  22032. serializationObject.parentId = this.parent.id;
  22033. }
  22034. // Inclusion / exclusions
  22035. if (this.excludedMeshes.length > 0) {
  22036. serializationObject.excludedMeshesIds = [];
  22037. this.excludedMeshes.forEach(function (mesh) {
  22038. serializationObject.excludedMeshesIds.push(mesh.id);
  22039. });
  22040. }
  22041. if (this.includedOnlyMeshes.length > 0) {
  22042. serializationObject.includedOnlyMeshesIds = [];
  22043. this.includedOnlyMeshes.forEach(function (mesh) {
  22044. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22045. });
  22046. }
  22047. // Animations
  22048. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22049. serializationObject.ranges = this.serializeAnimationRanges();
  22050. return serializationObject;
  22051. };
  22052. /**
  22053. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22054. * This new light is named "name" and added to the passed scene.
  22055. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22056. * @param name The friendly name of the light
  22057. * @param scene The scene the new light will belong to
  22058. * @returns the constructor function
  22059. */
  22060. Light.GetConstructorFromName = function (type, name, scene) {
  22061. switch (type) {
  22062. case 0:
  22063. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22064. case 1:
  22065. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22066. case 2:
  22067. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22068. case 3:
  22069. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22070. }
  22071. return null;
  22072. };
  22073. /**
  22074. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22075. * @param parsedLight The JSON representation of the light
  22076. * @param scene The scene to create the parsed light in
  22077. * @returns the created light after parsing
  22078. */
  22079. Light.Parse = function (parsedLight, scene) {
  22080. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22081. if (!constructor) {
  22082. return null;
  22083. }
  22084. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22085. // Inclusion / exclusions
  22086. if (parsedLight.excludedMeshesIds) {
  22087. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22088. }
  22089. if (parsedLight.includedOnlyMeshesIds) {
  22090. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22091. }
  22092. // Parent
  22093. if (parsedLight.parentId) {
  22094. light._waitingParentId = parsedLight.parentId;
  22095. }
  22096. // Animations
  22097. if (parsedLight.animations) {
  22098. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22099. var parsedAnimation = parsedLight.animations[animationIndex];
  22100. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22101. }
  22102. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22103. }
  22104. if (parsedLight.autoAnimate) {
  22105. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22106. }
  22107. return light;
  22108. };
  22109. Light.prototype._hookArrayForExcluded = function (array) {
  22110. var _this = this;
  22111. var oldPush = array.push;
  22112. array.push = function () {
  22113. var items = [];
  22114. for (var _i = 0; _i < arguments.length; _i++) {
  22115. items[_i] = arguments[_i];
  22116. }
  22117. var result = oldPush.apply(array, items);
  22118. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22119. var item = items_1[_a];
  22120. item._resyncLighSource(_this);
  22121. }
  22122. return result;
  22123. };
  22124. var oldSplice = array.splice;
  22125. array.splice = function (index, deleteCount) {
  22126. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22127. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22128. var item = deleted_1[_i];
  22129. item._resyncLighSource(_this);
  22130. }
  22131. return deleted;
  22132. };
  22133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22134. var item = array_1[_i];
  22135. item._resyncLighSource(this);
  22136. }
  22137. };
  22138. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22139. var _this = this;
  22140. var oldPush = array.push;
  22141. array.push = function () {
  22142. var items = [];
  22143. for (var _i = 0; _i < arguments.length; _i++) {
  22144. items[_i] = arguments[_i];
  22145. }
  22146. var result = oldPush.apply(array, items);
  22147. _this._resyncMeshes();
  22148. return result;
  22149. };
  22150. var oldSplice = array.splice;
  22151. array.splice = function (index, deleteCount) {
  22152. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22153. _this._resyncMeshes();
  22154. return deleted;
  22155. };
  22156. this._resyncMeshes();
  22157. };
  22158. Light.prototype._resyncMeshes = function () {
  22159. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22160. var mesh = _a[_i];
  22161. mesh._resyncLighSource(this);
  22162. }
  22163. };
  22164. /**
  22165. * Forces the meshes to update their light related information in their rendering used effects
  22166. * @hidden Internal Use Only
  22167. */
  22168. Light.prototype._markMeshesAsLightDirty = function () {
  22169. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22170. var mesh = _a[_i];
  22171. if (mesh._lightSources.indexOf(this) !== -1) {
  22172. mesh._markSubMeshesAsLightDirty();
  22173. }
  22174. }
  22175. };
  22176. /**
  22177. * Recomputes the cached photometric scale if needed.
  22178. */
  22179. Light.prototype._computePhotometricScale = function () {
  22180. this._photometricScale = this._getPhotometricScale();
  22181. this.getScene().resetCachedMaterial();
  22182. };
  22183. /**
  22184. * Returns the Photometric Scale according to the light type and intensity mode.
  22185. */
  22186. Light.prototype._getPhotometricScale = function () {
  22187. var photometricScale = 0.0;
  22188. var lightTypeID = this.getTypeID();
  22189. //get photometric mode
  22190. var photometricMode = this.intensityMode;
  22191. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22192. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22193. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22194. }
  22195. else {
  22196. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22197. }
  22198. }
  22199. //compute photometric scale
  22200. switch (lightTypeID) {
  22201. case Light.LIGHTTYPEID_POINTLIGHT:
  22202. case Light.LIGHTTYPEID_SPOTLIGHT:
  22203. switch (photometricMode) {
  22204. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22205. photometricScale = 1.0 / (4.0 * Math.PI);
  22206. break;
  22207. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22208. photometricScale = 1.0;
  22209. break;
  22210. case Light.INTENSITYMODE_LUMINANCE:
  22211. photometricScale = this.radius * this.radius;
  22212. break;
  22213. }
  22214. break;
  22215. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22216. switch (photometricMode) {
  22217. case Light.INTENSITYMODE_ILLUMINANCE:
  22218. photometricScale = 1.0;
  22219. break;
  22220. case Light.INTENSITYMODE_LUMINANCE:
  22221. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22222. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22223. var apexAngleRadians = this.radius;
  22224. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22225. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22226. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22227. photometricScale = solidAngle;
  22228. break;
  22229. }
  22230. break;
  22231. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22232. // No fall off in hemisperic light.
  22233. photometricScale = 1.0;
  22234. break;
  22235. }
  22236. return photometricScale;
  22237. };
  22238. /**
  22239. * Reorder the light in the scene according to their defined priority.
  22240. * @hidden Internal Use Only
  22241. */
  22242. Light.prototype._reorderLightsInScene = function () {
  22243. var scene = this.getScene();
  22244. if (this._renderPriority != 0) {
  22245. scene.requireLightSorting = true;
  22246. }
  22247. this.getScene().sortLightsByPriority();
  22248. };
  22249. //lightmapMode Consts
  22250. Light._LIGHTMAP_DEFAULT = 0;
  22251. Light._LIGHTMAP_SPECULAR = 1;
  22252. Light._LIGHTMAP_SHADOWSONLY = 2;
  22253. // Intensity Mode Consts
  22254. Light._INTENSITYMODE_AUTOMATIC = 0;
  22255. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22256. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22257. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22258. Light._INTENSITYMODE_LUMINANCE = 4;
  22259. // Light types ids const.
  22260. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22261. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22262. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22263. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22264. __decorate([
  22265. BABYLON.serializeAsColor3()
  22266. ], Light.prototype, "diffuse", void 0);
  22267. __decorate([
  22268. BABYLON.serializeAsColor3()
  22269. ], Light.prototype, "specular", void 0);
  22270. __decorate([
  22271. BABYLON.serialize()
  22272. ], Light.prototype, "intensity", void 0);
  22273. __decorate([
  22274. BABYLON.serialize()
  22275. ], Light.prototype, "range", void 0);
  22276. __decorate([
  22277. BABYLON.serialize()
  22278. ], Light.prototype, "intensityMode", null);
  22279. __decorate([
  22280. BABYLON.serialize()
  22281. ], Light.prototype, "radius", null);
  22282. __decorate([
  22283. BABYLON.serialize()
  22284. ], Light.prototype, "_renderPriority", void 0);
  22285. __decorate([
  22286. BABYLON.expandToProperty("_reorderLightsInScene")
  22287. ], Light.prototype, "renderPriority", void 0);
  22288. __decorate([
  22289. BABYLON.serialize("shadowEnabled")
  22290. ], Light.prototype, "_shadowEnabled", void 0);
  22291. __decorate([
  22292. BABYLON.serialize("excludeWithLayerMask")
  22293. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22294. __decorate([
  22295. BABYLON.serialize("includeOnlyWithLayerMask")
  22296. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22297. __decorate([
  22298. BABYLON.serialize("lightmapMode")
  22299. ], Light.prototype, "_lightmapMode", void 0);
  22300. return Light;
  22301. }(BABYLON.Node));
  22302. BABYLON.Light = Light;
  22303. })(BABYLON || (BABYLON = {}));
  22304. //# sourceMappingURL=babylon.light.js.map
  22305. var BABYLON;
  22306. (function (BABYLON) {
  22307. var Camera = /** @class */ (function (_super) {
  22308. __extends(Camera, _super);
  22309. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22310. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22311. var _this = _super.call(this, name, scene) || this;
  22312. /**
  22313. * The vector the camera should consider as up.
  22314. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22315. */
  22316. _this.upVector = BABYLON.Vector3.Up();
  22317. _this.orthoLeft = null;
  22318. _this.orthoRight = null;
  22319. _this.orthoBottom = null;
  22320. _this.orthoTop = null;
  22321. /**
  22322. * FOV is set in Radians. (default is 0.8)
  22323. */
  22324. _this.fov = 0.8;
  22325. _this.minZ = 1;
  22326. _this.maxZ = 10000.0;
  22327. _this.inertia = 0.9;
  22328. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22329. _this.isIntermediate = false;
  22330. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22331. /**
  22332. * Restricts the camera to viewing objects with the same layerMask.
  22333. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22334. */
  22335. _this.layerMask = 0x0FFFFFFF;
  22336. /**
  22337. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22338. */
  22339. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22340. // Camera rig members
  22341. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22342. _this._rigCameras = new Array();
  22343. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22344. _this._skipRendering = false;
  22345. _this.customRenderTargets = new Array();
  22346. // Observables
  22347. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22348. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22349. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22350. _this.onRestoreStateObservable = new BABYLON.Observable();
  22351. // Cache
  22352. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22353. _this._projectionMatrix = new BABYLON.Matrix();
  22354. _this._doNotComputeProjectionMatrix = false;
  22355. _this._worldMatrix = BABYLON.Matrix.Identity();
  22356. _this._postProcesses = new Array();
  22357. _this._transformMatrix = BABYLON.Matrix.Zero();
  22358. _this._activeMeshes = new BABYLON.SmartArray(256);
  22359. _this._globalPosition = BABYLON.Vector3.Zero();
  22360. _this._refreshFrustumPlanes = true;
  22361. _this.getScene().addCamera(_this);
  22362. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22363. _this.getScene().activeCamera = _this;
  22364. }
  22365. _this.position = position;
  22366. return _this;
  22367. }
  22368. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22369. get: function () {
  22370. return Camera._PERSPECTIVE_CAMERA;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22376. get: function () {
  22377. return Camera._ORTHOGRAPHIC_CAMERA;
  22378. },
  22379. enumerable: true,
  22380. configurable: true
  22381. });
  22382. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22383. /**
  22384. * This is the default FOV mode for perspective cameras.
  22385. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22386. *
  22387. */
  22388. get: function () {
  22389. return Camera._FOVMODE_VERTICAL_FIXED;
  22390. },
  22391. enumerable: true,
  22392. configurable: true
  22393. });
  22394. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22395. /**
  22396. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22397. *
  22398. */
  22399. get: function () {
  22400. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22401. },
  22402. enumerable: true,
  22403. configurable: true
  22404. });
  22405. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22406. get: function () {
  22407. return Camera._RIG_MODE_NONE;
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22413. get: function () {
  22414. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22415. },
  22416. enumerable: true,
  22417. configurable: true
  22418. });
  22419. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22420. get: function () {
  22421. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22427. get: function () {
  22428. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22434. get: function () {
  22435. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22436. },
  22437. enumerable: true,
  22438. configurable: true
  22439. });
  22440. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22441. get: function () {
  22442. return Camera._RIG_MODE_VR;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22448. get: function () {
  22449. return Camera._RIG_MODE_WEBVR;
  22450. },
  22451. enumerable: true,
  22452. configurable: true
  22453. });
  22454. /**
  22455. * Store current camera state (fov, position, etc..)
  22456. */
  22457. Camera.prototype.storeState = function () {
  22458. this._stateStored = true;
  22459. this._storedFov = this.fov;
  22460. return this;
  22461. };
  22462. /**
  22463. * Restores the camera state values if it has been stored. You must call storeState() first
  22464. */
  22465. Camera.prototype._restoreStateValues = function () {
  22466. if (!this._stateStored) {
  22467. return false;
  22468. }
  22469. this.fov = this._storedFov;
  22470. return true;
  22471. };
  22472. /**
  22473. * Restored camera state. You must call storeState() first
  22474. */
  22475. Camera.prototype.restoreState = function () {
  22476. if (this._restoreStateValues()) {
  22477. this.onRestoreStateObservable.notifyObservers(this);
  22478. return true;
  22479. }
  22480. return false;
  22481. };
  22482. Camera.prototype.getClassName = function () {
  22483. return "Camera";
  22484. };
  22485. /**
  22486. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22487. */
  22488. Camera.prototype.toString = function (fullDetails) {
  22489. var ret = "Name: " + this.name;
  22490. ret += ", type: " + this.getClassName();
  22491. if (this.animations) {
  22492. for (var i = 0; i < this.animations.length; i++) {
  22493. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22494. }
  22495. }
  22496. if (fullDetails) {
  22497. }
  22498. return ret;
  22499. };
  22500. Object.defineProperty(Camera.prototype, "globalPosition", {
  22501. get: function () {
  22502. return this._globalPosition;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Camera.prototype.getActiveMeshes = function () {
  22508. return this._activeMeshes;
  22509. };
  22510. Camera.prototype.isActiveMesh = function (mesh) {
  22511. return (this._activeMeshes.indexOf(mesh) !== -1);
  22512. };
  22513. /**
  22514. * Is this camera ready to be used/rendered
  22515. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22516. * @return true if the camera is ready
  22517. */
  22518. Camera.prototype.isReady = function (completeCheck) {
  22519. if (completeCheck === void 0) { completeCheck = false; }
  22520. if (completeCheck) {
  22521. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22522. var pp = _a[_i];
  22523. if (pp && !pp.isReady()) {
  22524. return false;
  22525. }
  22526. }
  22527. }
  22528. return _super.prototype.isReady.call(this, completeCheck);
  22529. };
  22530. //Cache
  22531. Camera.prototype._initCache = function () {
  22532. _super.prototype._initCache.call(this);
  22533. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22534. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22535. this._cache.mode = undefined;
  22536. this._cache.minZ = undefined;
  22537. this._cache.maxZ = undefined;
  22538. this._cache.fov = undefined;
  22539. this._cache.fovMode = undefined;
  22540. this._cache.aspectRatio = undefined;
  22541. this._cache.orthoLeft = undefined;
  22542. this._cache.orthoRight = undefined;
  22543. this._cache.orthoBottom = undefined;
  22544. this._cache.orthoTop = undefined;
  22545. this._cache.renderWidth = undefined;
  22546. this._cache.renderHeight = undefined;
  22547. };
  22548. Camera.prototype._updateCache = function (ignoreParentClass) {
  22549. if (!ignoreParentClass) {
  22550. _super.prototype._updateCache.call(this);
  22551. }
  22552. this._cache.position.copyFrom(this.position);
  22553. this._cache.upVector.copyFrom(this.upVector);
  22554. };
  22555. // Synchronized
  22556. Camera.prototype._isSynchronized = function () {
  22557. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22558. };
  22559. Camera.prototype._isSynchronizedViewMatrix = function () {
  22560. if (!_super.prototype._isSynchronized.call(this))
  22561. return false;
  22562. return this._cache.position.equals(this.position)
  22563. && this._cache.upVector.equals(this.upVector)
  22564. && this.isSynchronizedWithParent();
  22565. };
  22566. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22567. var check = this._cache.mode === this.mode
  22568. && this._cache.minZ === this.minZ
  22569. && this._cache.maxZ === this.maxZ;
  22570. if (!check) {
  22571. return false;
  22572. }
  22573. var engine = this.getEngine();
  22574. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22575. check = this._cache.fov === this.fov
  22576. && this._cache.fovMode === this.fovMode
  22577. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22578. }
  22579. else {
  22580. check = this._cache.orthoLeft === this.orthoLeft
  22581. && this._cache.orthoRight === this.orthoRight
  22582. && this._cache.orthoBottom === this.orthoBottom
  22583. && this._cache.orthoTop === this.orthoTop
  22584. && this._cache.renderWidth === engine.getRenderWidth()
  22585. && this._cache.renderHeight === engine.getRenderHeight();
  22586. }
  22587. return check;
  22588. };
  22589. // Controls
  22590. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22591. };
  22592. Camera.prototype.detachControl = function (element) {
  22593. };
  22594. Camera.prototype.update = function () {
  22595. this._checkInputs();
  22596. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22597. this._updateRigCameras();
  22598. }
  22599. };
  22600. Camera.prototype._checkInputs = function () {
  22601. this.onAfterCheckInputsObservable.notifyObservers(this);
  22602. };
  22603. Object.defineProperty(Camera.prototype, "rigCameras", {
  22604. get: function () {
  22605. return this._rigCameras;
  22606. },
  22607. enumerable: true,
  22608. configurable: true
  22609. });
  22610. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22611. get: function () {
  22612. return this._rigPostProcess;
  22613. },
  22614. enumerable: true,
  22615. configurable: true
  22616. });
  22617. /**
  22618. * Internal, gets the first post proces.
  22619. * @returns the first post process to be run on this camera.
  22620. */
  22621. Camera.prototype._getFirstPostProcess = function () {
  22622. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22623. if (this._postProcesses[ppIndex] !== null) {
  22624. return this._postProcesses[ppIndex];
  22625. }
  22626. }
  22627. return null;
  22628. };
  22629. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22630. // invalidate framebuffer
  22631. var firstPostProcess = this._getFirstPostProcess();
  22632. if (firstPostProcess) {
  22633. firstPostProcess.markTextureDirty();
  22634. }
  22635. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22636. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22637. var cam = this._rigCameras[i];
  22638. var rigPostProcess = cam._rigPostProcess;
  22639. // for VR rig, there does not have to be a post process
  22640. if (rigPostProcess) {
  22641. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22642. if (isPass) {
  22643. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22644. cam.isIntermediate = this._postProcesses.length === 0;
  22645. }
  22646. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22647. rigPostProcess.markTextureDirty();
  22648. }
  22649. else {
  22650. cam._postProcesses = this._postProcesses.slice(0);
  22651. }
  22652. }
  22653. };
  22654. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22655. if (insertAt === void 0) { insertAt = null; }
  22656. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22657. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22658. return 0;
  22659. }
  22660. if (insertAt == null || insertAt < 0) {
  22661. this._postProcesses.push(postProcess);
  22662. }
  22663. else if (this._postProcesses[insertAt] === null) {
  22664. this._postProcesses[insertAt] = postProcess;
  22665. }
  22666. else {
  22667. this._postProcesses.splice(insertAt, 0, postProcess);
  22668. }
  22669. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22670. return this._postProcesses.indexOf(postProcess);
  22671. };
  22672. Camera.prototype.detachPostProcess = function (postProcess) {
  22673. var idx = this._postProcesses.indexOf(postProcess);
  22674. if (idx !== -1) {
  22675. this._postProcesses[idx] = null;
  22676. }
  22677. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22678. };
  22679. Camera.prototype.getWorldMatrix = function () {
  22680. if (this._isSynchronizedViewMatrix()) {
  22681. return this._worldMatrix;
  22682. }
  22683. // Getting the the view matrix will also compute the world matrix.
  22684. this.getViewMatrix();
  22685. return this._worldMatrix;
  22686. };
  22687. Camera.prototype._getViewMatrix = function () {
  22688. return BABYLON.Matrix.Identity();
  22689. };
  22690. Camera.prototype.getViewMatrix = function (force) {
  22691. if (!force && this._isSynchronizedViewMatrix()) {
  22692. return this._computedViewMatrix;
  22693. }
  22694. this.updateCache();
  22695. this._computedViewMatrix = this._getViewMatrix();
  22696. this._currentRenderId = this.getScene().getRenderId();
  22697. this._childRenderId = this._currentRenderId;
  22698. this._refreshFrustumPlanes = true;
  22699. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22700. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22701. }
  22702. this.onViewMatrixChangedObservable.notifyObservers(this);
  22703. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22704. return this._computedViewMatrix;
  22705. };
  22706. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22707. this._doNotComputeProjectionMatrix = true;
  22708. if (projection !== undefined) {
  22709. this._projectionMatrix = projection;
  22710. }
  22711. };
  22712. ;
  22713. Camera.prototype.unfreezeProjectionMatrix = function () {
  22714. this._doNotComputeProjectionMatrix = false;
  22715. };
  22716. ;
  22717. Camera.prototype.getProjectionMatrix = function (force) {
  22718. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22719. return this._projectionMatrix;
  22720. }
  22721. // Cache
  22722. this._cache.mode = this.mode;
  22723. this._cache.minZ = this.minZ;
  22724. this._cache.maxZ = this.maxZ;
  22725. // Matrix
  22726. this._refreshFrustumPlanes = true;
  22727. var engine = this.getEngine();
  22728. var scene = this.getScene();
  22729. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22730. this._cache.fov = this.fov;
  22731. this._cache.fovMode = this.fovMode;
  22732. this._cache.aspectRatio = engine.getAspectRatio(this);
  22733. if (this.minZ <= 0) {
  22734. this.minZ = 0.1;
  22735. }
  22736. if (scene.useRightHandedSystem) {
  22737. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22738. }
  22739. else {
  22740. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22741. }
  22742. }
  22743. else {
  22744. var halfWidth = engine.getRenderWidth() / 2.0;
  22745. var halfHeight = engine.getRenderHeight() / 2.0;
  22746. if (scene.useRightHandedSystem) {
  22747. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22748. }
  22749. else {
  22750. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22751. }
  22752. this._cache.orthoLeft = this.orthoLeft;
  22753. this._cache.orthoRight = this.orthoRight;
  22754. this._cache.orthoBottom = this.orthoBottom;
  22755. this._cache.orthoTop = this.orthoTop;
  22756. this._cache.renderWidth = engine.getRenderWidth();
  22757. this._cache.renderHeight = engine.getRenderHeight();
  22758. }
  22759. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22760. return this._projectionMatrix;
  22761. };
  22762. Camera.prototype.getTranformationMatrix = function () {
  22763. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22764. return this._transformMatrix;
  22765. };
  22766. Camera.prototype.updateFrustumPlanes = function () {
  22767. if (!this._refreshFrustumPlanes) {
  22768. return;
  22769. }
  22770. this.getTranformationMatrix();
  22771. if (!this._frustumPlanes) {
  22772. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22773. }
  22774. else {
  22775. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22776. }
  22777. this._refreshFrustumPlanes = false;
  22778. };
  22779. Camera.prototype.isInFrustum = function (target) {
  22780. this.updateFrustumPlanes();
  22781. return target.isInFrustum(this._frustumPlanes);
  22782. };
  22783. Camera.prototype.isCompletelyInFrustum = function (target) {
  22784. this.updateFrustumPlanes();
  22785. return target.isCompletelyInFrustum(this._frustumPlanes);
  22786. };
  22787. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22788. if (length === void 0) { length = 100; }
  22789. if (!transform) {
  22790. transform = this.getWorldMatrix();
  22791. }
  22792. if (!origin) {
  22793. origin = this.position;
  22794. }
  22795. var forward = new BABYLON.Vector3(0, 0, 1);
  22796. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22797. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22798. return new BABYLON.Ray(origin, direction, length);
  22799. };
  22800. /**
  22801. * Releases resources associated with this node.
  22802. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22803. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22804. */
  22805. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22806. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22807. // Observables
  22808. this.onViewMatrixChangedObservable.clear();
  22809. this.onProjectionMatrixChangedObservable.clear();
  22810. this.onAfterCheckInputsObservable.clear();
  22811. this.onRestoreStateObservable.clear();
  22812. // Inputs
  22813. if (this.inputs) {
  22814. this.inputs.clear();
  22815. }
  22816. // Animations
  22817. this.getScene().stopAnimation(this);
  22818. // Remove from scene
  22819. this.getScene().removeCamera(this);
  22820. while (this._rigCameras.length > 0) {
  22821. var camera = this._rigCameras.pop();
  22822. if (camera) {
  22823. camera.dispose();
  22824. }
  22825. }
  22826. // Postprocesses
  22827. if (this._rigPostProcess) {
  22828. this._rigPostProcess.dispose(this);
  22829. this._rigPostProcess = null;
  22830. this._postProcesses = [];
  22831. }
  22832. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22833. this._rigPostProcess = null;
  22834. this._postProcesses = [];
  22835. }
  22836. else {
  22837. var i = this._postProcesses.length;
  22838. while (--i >= 0) {
  22839. var postProcess = this._postProcesses[i];
  22840. if (postProcess) {
  22841. postProcess.dispose(this);
  22842. }
  22843. }
  22844. }
  22845. // Render targets
  22846. var i = this.customRenderTargets.length;
  22847. while (--i >= 0) {
  22848. this.customRenderTargets[i].dispose();
  22849. }
  22850. this.customRenderTargets = [];
  22851. // Active Meshes
  22852. this._activeMeshes.dispose();
  22853. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22854. };
  22855. Object.defineProperty(Camera.prototype, "leftCamera", {
  22856. // ---- Camera rigs section ----
  22857. get: function () {
  22858. if (this._rigCameras.length < 1) {
  22859. return null;
  22860. }
  22861. return this._rigCameras[0];
  22862. },
  22863. enumerable: true,
  22864. configurable: true
  22865. });
  22866. Object.defineProperty(Camera.prototype, "rightCamera", {
  22867. get: function () {
  22868. if (this._rigCameras.length < 2) {
  22869. return null;
  22870. }
  22871. return this._rigCameras[1];
  22872. },
  22873. enumerable: true,
  22874. configurable: true
  22875. });
  22876. Camera.prototype.getLeftTarget = function () {
  22877. if (this._rigCameras.length < 1) {
  22878. return null;
  22879. }
  22880. return this._rigCameras[0].getTarget();
  22881. };
  22882. Camera.prototype.getRightTarget = function () {
  22883. if (this._rigCameras.length < 2) {
  22884. return null;
  22885. }
  22886. return this._rigCameras[1].getTarget();
  22887. };
  22888. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22889. if (this.cameraRigMode === mode) {
  22890. return;
  22891. }
  22892. while (this._rigCameras.length > 0) {
  22893. var camera = this._rigCameras.pop();
  22894. if (camera) {
  22895. camera.dispose();
  22896. }
  22897. }
  22898. this.cameraRigMode = mode;
  22899. this._cameraRigParams = {};
  22900. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22901. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22902. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22903. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22904. // create the rig cameras, unless none
  22905. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22906. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22907. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22908. if (leftCamera && rightCamera) {
  22909. this._rigCameras.push(leftCamera);
  22910. this._rigCameras.push(rightCamera);
  22911. }
  22912. }
  22913. switch (this.cameraRigMode) {
  22914. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22915. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22916. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22917. break;
  22918. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22919. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22920. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22921. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22922. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22923. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22924. break;
  22925. case Camera.RIG_MODE_VR:
  22926. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22927. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22928. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22929. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22930. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22931. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22932. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22933. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22934. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22935. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22936. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22937. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22938. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22939. if (metrics.compensateDistortion) {
  22940. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22941. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22942. }
  22943. break;
  22944. case Camera.RIG_MODE_WEBVR:
  22945. if (rigParams.vrDisplay) {
  22946. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22947. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22948. //Left eye
  22949. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22950. this._rigCameras[0].setCameraRigParameter("left", true);
  22951. //leaving this for future reference
  22952. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22953. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22954. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22955. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22956. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22957. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22958. this._rigCameras[0].parent = this;
  22959. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22960. //Right eye
  22961. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22962. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22963. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22964. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22965. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22966. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22967. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22968. this._rigCameras[1].parent = this;
  22969. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22970. if (Camera.UseAlternateWebVRRendering) {
  22971. this._rigCameras[1]._skipRendering = true;
  22972. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22973. }
  22974. }
  22975. break;
  22976. }
  22977. this._cascadePostProcessesToRigCams();
  22978. this.update();
  22979. };
  22980. Camera.prototype._getVRProjectionMatrix = function () {
  22981. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22982. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22983. return this._projectionMatrix;
  22984. };
  22985. Camera.prototype._updateCameraRotationMatrix = function () {
  22986. //Here for WebVR
  22987. };
  22988. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22989. //Here for WebVR
  22990. };
  22991. /**
  22992. * This function MUST be overwritten by the different WebVR cameras available.
  22993. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22994. */
  22995. Camera.prototype._getWebVRProjectionMatrix = function () {
  22996. return BABYLON.Matrix.Identity();
  22997. };
  22998. /**
  22999. * This function MUST be overwritten by the different WebVR cameras available.
  23000. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23001. */
  23002. Camera.prototype._getWebVRViewMatrix = function () {
  23003. return BABYLON.Matrix.Identity();
  23004. };
  23005. Camera.prototype.setCameraRigParameter = function (name, value) {
  23006. if (!this._cameraRigParams) {
  23007. this._cameraRigParams = {};
  23008. }
  23009. this._cameraRigParams[name] = value;
  23010. //provisionnally:
  23011. if (name === "interaxialDistance") {
  23012. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23013. }
  23014. };
  23015. /**
  23016. * needs to be overridden by children so sub has required properties to be copied
  23017. */
  23018. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23019. return null;
  23020. };
  23021. /**
  23022. * May need to be overridden by children
  23023. */
  23024. Camera.prototype._updateRigCameras = function () {
  23025. for (var i = 0; i < this._rigCameras.length; i++) {
  23026. this._rigCameras[i].minZ = this.minZ;
  23027. this._rigCameras[i].maxZ = this.maxZ;
  23028. this._rigCameras[i].fov = this.fov;
  23029. }
  23030. // only update viewport when ANAGLYPH
  23031. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23032. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23033. }
  23034. };
  23035. Camera.prototype._setupInputs = function () {
  23036. };
  23037. Camera.prototype.serialize = function () {
  23038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23039. // Type
  23040. serializationObject.type = this.getClassName();
  23041. // Parent
  23042. if (this.parent) {
  23043. serializationObject.parentId = this.parent.id;
  23044. }
  23045. if (this.inputs) {
  23046. this.inputs.serialize(serializationObject);
  23047. }
  23048. // Animations
  23049. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23050. serializationObject.ranges = this.serializeAnimationRanges();
  23051. return serializationObject;
  23052. };
  23053. Camera.prototype.clone = function (name) {
  23054. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23055. };
  23056. Camera.prototype.getDirection = function (localAxis) {
  23057. var result = BABYLON.Vector3.Zero();
  23058. this.getDirectionToRef(localAxis, result);
  23059. return result;
  23060. };
  23061. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23062. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23063. };
  23064. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23065. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23066. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23067. switch (type) {
  23068. case "ArcRotateCamera":
  23069. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23070. case "DeviceOrientationCamera":
  23071. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23072. case "FollowCamera":
  23073. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23074. case "ArcFollowCamera":
  23075. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23076. case "GamepadCamera":
  23077. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23078. case "TouchCamera":
  23079. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23080. case "VirtualJoysticksCamera":
  23081. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23082. case "WebVRFreeCamera":
  23083. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23084. case "WebVRGamepadCamera":
  23085. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23086. case "VRDeviceOrientationFreeCamera":
  23087. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23088. case "VRDeviceOrientationGamepadCamera":
  23089. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23090. case "AnaglyphArcRotateCamera":
  23091. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23092. case "AnaglyphFreeCamera":
  23093. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23094. case "AnaglyphGamepadCamera":
  23095. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23096. case "AnaglyphUniversalCamera":
  23097. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23098. case "StereoscopicArcRotateCamera":
  23099. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23100. case "StereoscopicFreeCamera":
  23101. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23102. case "StereoscopicGamepadCamera":
  23103. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23104. case "StereoscopicUniversalCamera":
  23105. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23106. case "FreeCamera": // Forcing Universal here
  23107. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23108. default: // Universal Camera is the default value
  23109. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23110. }
  23111. };
  23112. Camera.prototype.computeWorldMatrix = function () {
  23113. return this.getWorldMatrix();
  23114. };
  23115. Camera.Parse = function (parsedCamera, scene) {
  23116. var type = parsedCamera.type;
  23117. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23118. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23119. // Parent
  23120. if (parsedCamera.parentId) {
  23121. camera._waitingParentId = parsedCamera.parentId;
  23122. }
  23123. //If camera has an input manager, let it parse inputs settings
  23124. if (camera.inputs) {
  23125. camera.inputs.parse(parsedCamera);
  23126. camera._setupInputs();
  23127. }
  23128. if (camera.setPosition) { // need to force position
  23129. camera.position.copyFromFloats(0, 0, 0);
  23130. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23131. }
  23132. // Target
  23133. if (parsedCamera.target) {
  23134. if (camera.setTarget) {
  23135. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23136. }
  23137. }
  23138. // Apply 3d rig, when found
  23139. if (parsedCamera.cameraRigMode) {
  23140. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23141. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23142. }
  23143. // Animations
  23144. if (parsedCamera.animations) {
  23145. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23146. var parsedAnimation = parsedCamera.animations[animationIndex];
  23147. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23148. }
  23149. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23150. }
  23151. if (parsedCamera.autoAnimate) {
  23152. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23153. }
  23154. return camera;
  23155. };
  23156. // Statics
  23157. Camera._PERSPECTIVE_CAMERA = 0;
  23158. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23159. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23160. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23161. Camera._RIG_MODE_NONE = 0;
  23162. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23163. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23164. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23165. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23166. Camera._RIG_MODE_VR = 20;
  23167. Camera._RIG_MODE_WEBVR = 21;
  23168. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23169. Camera.UseAlternateWebVRRendering = false;
  23170. __decorate([
  23171. BABYLON.serializeAsVector3()
  23172. ], Camera.prototype, "position", void 0);
  23173. __decorate([
  23174. BABYLON.serializeAsVector3()
  23175. ], Camera.prototype, "upVector", void 0);
  23176. __decorate([
  23177. BABYLON.serialize()
  23178. ], Camera.prototype, "orthoLeft", void 0);
  23179. __decorate([
  23180. BABYLON.serialize()
  23181. ], Camera.prototype, "orthoRight", void 0);
  23182. __decorate([
  23183. BABYLON.serialize()
  23184. ], Camera.prototype, "orthoBottom", void 0);
  23185. __decorate([
  23186. BABYLON.serialize()
  23187. ], Camera.prototype, "orthoTop", void 0);
  23188. __decorate([
  23189. BABYLON.serialize()
  23190. ], Camera.prototype, "fov", void 0);
  23191. __decorate([
  23192. BABYLON.serialize()
  23193. ], Camera.prototype, "minZ", void 0);
  23194. __decorate([
  23195. BABYLON.serialize()
  23196. ], Camera.prototype, "maxZ", void 0);
  23197. __decorate([
  23198. BABYLON.serialize()
  23199. ], Camera.prototype, "inertia", void 0);
  23200. __decorate([
  23201. BABYLON.serialize()
  23202. ], Camera.prototype, "mode", void 0);
  23203. __decorate([
  23204. BABYLON.serialize()
  23205. ], Camera.prototype, "layerMask", void 0);
  23206. __decorate([
  23207. BABYLON.serialize()
  23208. ], Camera.prototype, "fovMode", void 0);
  23209. __decorate([
  23210. BABYLON.serialize()
  23211. ], Camera.prototype, "cameraRigMode", void 0);
  23212. __decorate([
  23213. BABYLON.serialize()
  23214. ], Camera.prototype, "interaxialDistance", void 0);
  23215. __decorate([
  23216. BABYLON.serialize()
  23217. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23218. return Camera;
  23219. }(BABYLON.Node));
  23220. BABYLON.Camera = Camera;
  23221. })(BABYLON || (BABYLON = {}));
  23222. //# sourceMappingURL=babylon.camera.js.map
  23223. var BABYLON;
  23224. (function (BABYLON) {
  23225. var RenderingManager = /** @class */ (function () {
  23226. function RenderingManager(scene) {
  23227. this._renderingGroups = new Array();
  23228. this._autoClearDepthStencil = {};
  23229. this._customOpaqueSortCompareFn = {};
  23230. this._customAlphaTestSortCompareFn = {};
  23231. this._customTransparentSortCompareFn = {};
  23232. this._renderinGroupInfo = null;
  23233. this._scene = scene;
  23234. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23235. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23236. }
  23237. }
  23238. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23239. if (depth === void 0) { depth = true; }
  23240. if (stencil === void 0) { stencil = true; }
  23241. if (this._depthStencilBufferAlreadyCleaned) {
  23242. return;
  23243. }
  23244. this._scene.getEngine().clear(null, false, depth, stencil);
  23245. this._depthStencilBufferAlreadyCleaned = true;
  23246. };
  23247. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23248. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23249. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23250. var info = null;
  23251. if (observable) {
  23252. if (!this._renderinGroupInfo) {
  23253. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23254. }
  23255. info = this._renderinGroupInfo;
  23256. info.scene = this._scene;
  23257. info.camera = this._scene.activeCamera;
  23258. }
  23259. // Dispatch sprites
  23260. if (renderSprites) {
  23261. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23262. var manager = this._scene.spriteManagers[index];
  23263. this.dispatchSprites(manager);
  23264. }
  23265. }
  23266. // Render
  23267. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23268. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23269. var renderingGroup = this._renderingGroups[index];
  23270. if (!renderingGroup && !observable)
  23271. continue;
  23272. var renderingGroupMask = 0;
  23273. // Fire PRECLEAR stage
  23274. if (observable && info) {
  23275. renderingGroupMask = Math.pow(2, index);
  23276. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23277. info.renderingGroupId = index;
  23278. observable.notifyObservers(info, renderingGroupMask);
  23279. }
  23280. // Clear depth/stencil if needed
  23281. if (RenderingManager.AUTOCLEAR) {
  23282. var autoClear = this._autoClearDepthStencil[index];
  23283. if (autoClear && autoClear.autoClear) {
  23284. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23285. }
  23286. }
  23287. if (observable && info) {
  23288. // Fire PREOPAQUE stage
  23289. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23290. observable.notifyObservers(info, renderingGroupMask);
  23291. // Fire PRETRANSPARENT stage
  23292. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23293. observable.notifyObservers(info, renderingGroupMask);
  23294. }
  23295. if (renderingGroup)
  23296. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23297. // Fire POSTTRANSPARENT stage
  23298. if (observable && info) {
  23299. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23300. observable.notifyObservers(info, renderingGroupMask);
  23301. }
  23302. }
  23303. };
  23304. RenderingManager.prototype.reset = function () {
  23305. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23306. var renderingGroup = this._renderingGroups[index];
  23307. if (renderingGroup) {
  23308. renderingGroup.prepare();
  23309. }
  23310. }
  23311. };
  23312. RenderingManager.prototype.dispose = function () {
  23313. this.freeRenderingGroups();
  23314. this._renderingGroups.length = 0;
  23315. };
  23316. /**
  23317. * Clear the info related to rendering groups preventing retention points during dispose.
  23318. */
  23319. RenderingManager.prototype.freeRenderingGroups = function () {
  23320. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23321. var renderingGroup = this._renderingGroups[index];
  23322. if (renderingGroup) {
  23323. renderingGroup.dispose();
  23324. }
  23325. }
  23326. };
  23327. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23328. if (this._renderingGroups[renderingGroupId] === undefined) {
  23329. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23330. }
  23331. };
  23332. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23333. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23334. this._prepareRenderingGroup(renderingGroupId);
  23335. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23336. };
  23337. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23338. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23339. this._prepareRenderingGroup(renderingGroupId);
  23340. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23341. };
  23342. /**
  23343. * @param subMesh The submesh to dispatch
  23344. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23345. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23346. */
  23347. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23348. if (mesh === undefined) {
  23349. mesh = subMesh.getMesh();
  23350. }
  23351. var renderingGroupId = mesh.renderingGroupId || 0;
  23352. this._prepareRenderingGroup(renderingGroupId);
  23353. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23354. };
  23355. /**
  23356. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23357. * This allowed control for front to back rendering or reversly depending of the special needs.
  23358. *
  23359. * @param renderingGroupId The rendering group id corresponding to its index
  23360. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23361. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23362. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23363. */
  23364. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23365. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23366. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23367. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23368. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23369. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23370. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23371. if (this._renderingGroups[renderingGroupId]) {
  23372. var group = this._renderingGroups[renderingGroupId];
  23373. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23374. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23375. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23376. }
  23377. };
  23378. /**
  23379. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23380. *
  23381. * @param renderingGroupId The rendering group id corresponding to its index
  23382. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23383. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23384. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23385. */
  23386. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23387. if (depth === void 0) { depth = true; }
  23388. if (stencil === void 0) { stencil = true; }
  23389. this._autoClearDepthStencil[renderingGroupId] = {
  23390. autoClear: autoClearDepthStencil,
  23391. depth: depth,
  23392. stencil: stencil
  23393. };
  23394. };
  23395. /**
  23396. * The max id used for rendering groups (not included)
  23397. */
  23398. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23399. /**
  23400. * The min id used for rendering groups (included)
  23401. */
  23402. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23403. /**
  23404. * Used to globally prevent autoclearing scenes.
  23405. */
  23406. RenderingManager.AUTOCLEAR = true;
  23407. return RenderingManager;
  23408. }());
  23409. BABYLON.RenderingManager = RenderingManager;
  23410. })(BABYLON || (BABYLON = {}));
  23411. //# sourceMappingURL=babylon.renderingManager.js.map
  23412. var BABYLON;
  23413. (function (BABYLON) {
  23414. var RenderingGroup = /** @class */ (function () {
  23415. /**
  23416. * Creates a new rendering group.
  23417. * @param index The rendering group index
  23418. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23419. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23420. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23421. */
  23422. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23423. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23424. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23425. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23426. this.index = index;
  23427. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23428. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23429. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23430. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23431. this._particleSystems = new BABYLON.SmartArray(256);
  23432. this._spriteManagers = new BABYLON.SmartArray(256);
  23433. this._edgesRenderers = new BABYLON.SmartArray(16);
  23434. this._scene = scene;
  23435. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23436. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23437. this.transparentSortCompareFn = transparentSortCompareFn;
  23438. }
  23439. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23440. /**
  23441. * Set the opaque sort comparison function.
  23442. * If null the sub meshes will be render in the order they were created
  23443. */
  23444. set: function (value) {
  23445. this._opaqueSortCompareFn = value;
  23446. if (value) {
  23447. this._renderOpaque = this.renderOpaqueSorted;
  23448. }
  23449. else {
  23450. this._renderOpaque = RenderingGroup.renderUnsorted;
  23451. }
  23452. },
  23453. enumerable: true,
  23454. configurable: true
  23455. });
  23456. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23457. /**
  23458. * Set the alpha test sort comparison function.
  23459. * If null the sub meshes will be render in the order they were created
  23460. */
  23461. set: function (value) {
  23462. this._alphaTestSortCompareFn = value;
  23463. if (value) {
  23464. this._renderAlphaTest = this.renderAlphaTestSorted;
  23465. }
  23466. else {
  23467. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23468. }
  23469. },
  23470. enumerable: true,
  23471. configurable: true
  23472. });
  23473. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23474. /**
  23475. * Set the transparent sort comparison function.
  23476. * If null the sub meshes will be render in the order they were created
  23477. */
  23478. set: function (value) {
  23479. if (value) {
  23480. this._transparentSortCompareFn = value;
  23481. }
  23482. else {
  23483. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23484. }
  23485. this._renderTransparent = this.renderTransparentSorted;
  23486. },
  23487. enumerable: true,
  23488. configurable: true
  23489. });
  23490. /**
  23491. * Render all the sub meshes contained in the group.
  23492. * @param customRenderFunction Used to override the default render behaviour of the group.
  23493. * @returns true if rendered some submeshes.
  23494. */
  23495. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23496. if (customRenderFunction) {
  23497. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23498. return;
  23499. }
  23500. var engine = this._scene.getEngine();
  23501. // Depth only
  23502. if (this._depthOnlySubMeshes.length !== 0) {
  23503. engine.setColorWrite(false);
  23504. this._renderAlphaTest(this._depthOnlySubMeshes);
  23505. engine.setColorWrite(true);
  23506. }
  23507. // Opaque
  23508. if (this._opaqueSubMeshes.length !== 0) {
  23509. this._renderOpaque(this._opaqueSubMeshes);
  23510. }
  23511. // Alpha test
  23512. if (this._alphaTestSubMeshes.length !== 0) {
  23513. this._renderAlphaTest(this._alphaTestSubMeshes);
  23514. }
  23515. var stencilState = engine.getStencilBuffer();
  23516. engine.setStencilBuffer(false);
  23517. // Sprites
  23518. if (renderSprites) {
  23519. this._renderSprites();
  23520. }
  23521. // Particles
  23522. if (renderParticles) {
  23523. this._renderParticles(activeMeshes);
  23524. }
  23525. if (this.onBeforeTransparentRendering) {
  23526. this.onBeforeTransparentRendering();
  23527. }
  23528. // Transparent
  23529. if (this._transparentSubMeshes.length !== 0) {
  23530. this._renderTransparent(this._transparentSubMeshes);
  23531. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23532. }
  23533. // Set back stencil to false in case it changes before the edge renderer.
  23534. engine.setStencilBuffer(false);
  23535. // Edges
  23536. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23537. this._edgesRenderers.data[edgesRendererIndex].render();
  23538. }
  23539. // Restore Stencil state.
  23540. engine.setStencilBuffer(stencilState);
  23541. };
  23542. /**
  23543. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23544. * @param subMeshes The submeshes to render
  23545. */
  23546. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23547. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23548. };
  23549. /**
  23550. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23551. * @param subMeshes The submeshes to render
  23552. */
  23553. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23554. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23555. };
  23556. /**
  23557. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23558. * @param subMeshes The submeshes to render
  23559. */
  23560. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23561. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23562. };
  23563. /**
  23564. * Renders the submeshes in a specified order.
  23565. * @param subMeshes The submeshes to sort before render
  23566. * @param sortCompareFn The comparison function use to sort
  23567. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23568. * @param transparent Specifies to activate blending if true
  23569. */
  23570. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23571. var subIndex = 0;
  23572. var subMesh;
  23573. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23574. for (; subIndex < subMeshes.length; subIndex++) {
  23575. subMesh = subMeshes.data[subIndex];
  23576. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23577. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23578. }
  23579. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23580. if (sortCompareFn) {
  23581. sortedArray.sort(sortCompareFn);
  23582. }
  23583. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23584. subMesh = sortedArray[subIndex];
  23585. if (transparent) {
  23586. var material = subMesh.getMaterial();
  23587. if (material && material.needDepthPrePass) {
  23588. var engine = material.getScene().getEngine();
  23589. engine.setColorWrite(false);
  23590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23591. subMesh.render(false);
  23592. engine.setColorWrite(true);
  23593. }
  23594. }
  23595. subMesh.render(transparent);
  23596. }
  23597. };
  23598. /**
  23599. * Renders the submeshes in the order they were dispatched (no sort applied).
  23600. * @param subMeshes The submeshes to render
  23601. */
  23602. RenderingGroup.renderUnsorted = function (subMeshes) {
  23603. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23604. var submesh = subMeshes.data[subIndex];
  23605. submesh.render(false);
  23606. }
  23607. };
  23608. /**
  23609. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23610. * are rendered back to front if in the same alpha index.
  23611. *
  23612. * @param a The first submesh
  23613. * @param b The second submesh
  23614. * @returns The result of the comparison
  23615. */
  23616. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23617. // Alpha index first
  23618. if (a._alphaIndex > b._alphaIndex) {
  23619. return 1;
  23620. }
  23621. if (a._alphaIndex < b._alphaIndex) {
  23622. return -1;
  23623. }
  23624. // Then distance to camera
  23625. return RenderingGroup.backToFrontSortCompare(a, b);
  23626. };
  23627. /**
  23628. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23629. * are rendered back to front.
  23630. *
  23631. * @param a The first submesh
  23632. * @param b The second submesh
  23633. * @returns The result of the comparison
  23634. */
  23635. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23636. // Then distance to camera
  23637. if (a._distanceToCamera < b._distanceToCamera) {
  23638. return 1;
  23639. }
  23640. if (a._distanceToCamera > b._distanceToCamera) {
  23641. return -1;
  23642. }
  23643. return 0;
  23644. };
  23645. /**
  23646. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23647. * are rendered front to back (prevent overdraw).
  23648. *
  23649. * @param a The first submesh
  23650. * @param b The second submesh
  23651. * @returns The result of the comparison
  23652. */
  23653. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23654. // Then distance to camera
  23655. if (a._distanceToCamera < b._distanceToCamera) {
  23656. return -1;
  23657. }
  23658. if (a._distanceToCamera > b._distanceToCamera) {
  23659. return 1;
  23660. }
  23661. return 0;
  23662. };
  23663. /**
  23664. * Resets the different lists of submeshes to prepare a new frame.
  23665. */
  23666. RenderingGroup.prototype.prepare = function () {
  23667. this._opaqueSubMeshes.reset();
  23668. this._transparentSubMeshes.reset();
  23669. this._alphaTestSubMeshes.reset();
  23670. this._depthOnlySubMeshes.reset();
  23671. this._particleSystems.reset();
  23672. this._spriteManagers.reset();
  23673. this._edgesRenderers.reset();
  23674. };
  23675. RenderingGroup.prototype.dispose = function () {
  23676. this._opaqueSubMeshes.dispose();
  23677. this._transparentSubMeshes.dispose();
  23678. this._alphaTestSubMeshes.dispose();
  23679. this._depthOnlySubMeshes.dispose();
  23680. this._particleSystems.dispose();
  23681. this._spriteManagers.dispose();
  23682. this._edgesRenderers.dispose();
  23683. };
  23684. /**
  23685. * Inserts the submesh in its correct queue depending on its material.
  23686. * @param subMesh The submesh to dispatch
  23687. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23688. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23689. */
  23690. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23691. // Get mesh and materials if not provided
  23692. if (mesh === undefined) {
  23693. mesh = subMesh.getMesh();
  23694. }
  23695. if (material === undefined) {
  23696. material = subMesh.getMaterial();
  23697. }
  23698. if (material === null || material === undefined) {
  23699. return;
  23700. }
  23701. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23702. this._transparentSubMeshes.push(subMesh);
  23703. }
  23704. else if (material.needAlphaTesting()) { // Alpha test
  23705. if (material.needDepthPrePass) {
  23706. this._depthOnlySubMeshes.push(subMesh);
  23707. }
  23708. this._alphaTestSubMeshes.push(subMesh);
  23709. }
  23710. else {
  23711. if (material.needDepthPrePass) {
  23712. this._depthOnlySubMeshes.push(subMesh);
  23713. }
  23714. this._opaqueSubMeshes.push(subMesh); // Opaque
  23715. }
  23716. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23717. this._edgesRenderers.push(mesh._edgesRenderer);
  23718. }
  23719. };
  23720. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23721. this._spriteManagers.push(spriteManager);
  23722. };
  23723. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23724. this._particleSystems.push(particleSystem);
  23725. };
  23726. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23727. if (this._particleSystems.length === 0) {
  23728. return;
  23729. }
  23730. // Particles
  23731. var activeCamera = this._scene.activeCamera;
  23732. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23733. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23734. var particleSystem = this._particleSystems.data[particleIndex];
  23735. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23736. continue;
  23737. }
  23738. var emitter = particleSystem.emitter;
  23739. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23740. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23741. }
  23742. }
  23743. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23744. };
  23745. RenderingGroup.prototype._renderSprites = function () {
  23746. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23747. return;
  23748. }
  23749. // Sprites
  23750. var activeCamera = this._scene.activeCamera;
  23751. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23752. for (var id = 0; id < this._spriteManagers.length; id++) {
  23753. var spriteManager = this._spriteManagers.data[id];
  23754. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23755. spriteManager.render();
  23756. }
  23757. }
  23758. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23759. };
  23760. return RenderingGroup;
  23761. }());
  23762. BABYLON.RenderingGroup = RenderingGroup;
  23763. })(BABYLON || (BABYLON = {}));
  23764. //# sourceMappingURL=babylon.renderingGroup.js.map
  23765. var BABYLON;
  23766. (function (BABYLON) {
  23767. /** @hidden */
  23768. var ClickInfo = /** @class */ (function () {
  23769. function ClickInfo() {
  23770. this._singleClick = false;
  23771. this._doubleClick = false;
  23772. this._hasSwiped = false;
  23773. this._ignore = false;
  23774. }
  23775. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23776. get: function () {
  23777. return this._singleClick;
  23778. },
  23779. set: function (b) {
  23780. this._singleClick = b;
  23781. },
  23782. enumerable: true,
  23783. configurable: true
  23784. });
  23785. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23786. get: function () {
  23787. return this._doubleClick;
  23788. },
  23789. set: function (b) {
  23790. this._doubleClick = b;
  23791. },
  23792. enumerable: true,
  23793. configurable: true
  23794. });
  23795. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23796. get: function () {
  23797. return this._hasSwiped;
  23798. },
  23799. set: function (b) {
  23800. this._hasSwiped = b;
  23801. },
  23802. enumerable: true,
  23803. configurable: true
  23804. });
  23805. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23806. get: function () {
  23807. return this._ignore;
  23808. },
  23809. set: function (b) {
  23810. this._ignore = b;
  23811. },
  23812. enumerable: true,
  23813. configurable: true
  23814. });
  23815. return ClickInfo;
  23816. }());
  23817. /**
  23818. * This class is used by the onRenderingGroupObservable
  23819. */
  23820. var RenderingGroupInfo = /** @class */ (function () {
  23821. function RenderingGroupInfo() {
  23822. }
  23823. /**
  23824. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23825. * This stage will be fired no matter what
  23826. */
  23827. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23828. /**
  23829. * Called before opaque object are rendered.
  23830. * This stage will be fired only if there's 3D Opaque content to render
  23831. */
  23832. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23833. /**
  23834. * Called after the opaque objects are rendered and before the transparent ones
  23835. * This stage will be fired only if there's 3D transparent content to render
  23836. */
  23837. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23838. /**
  23839. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23840. * This stage will be fired no matter what
  23841. */
  23842. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23843. return RenderingGroupInfo;
  23844. }());
  23845. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23846. /**
  23847. * Represents a scene to be rendered by the engine.
  23848. * @see http://doc.babylonjs.com/features/scene
  23849. */
  23850. var Scene = /** @class */ (function () {
  23851. /**
  23852. * Creates a new Scene
  23853. * @param engine defines the engine to use to render this scene
  23854. */
  23855. function Scene(engine) {
  23856. // Members
  23857. /**
  23858. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23859. */
  23860. this.autoClear = true;
  23861. /**
  23862. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23863. */
  23864. this.autoClearDepthAndStencil = true;
  23865. /**
  23866. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23867. */
  23868. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23869. /**
  23870. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23871. */
  23872. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23873. this._forceWireframe = false;
  23874. this._forcePointsCloud = false;
  23875. /**
  23876. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23877. */
  23878. this.forceShowBoundingBoxes = false;
  23879. /**
  23880. * Gets or sets a boolean indicating if animations are enabled
  23881. */
  23882. this.animationsEnabled = true;
  23883. this._animationPropertiesOverride = null;
  23884. /**
  23885. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23886. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23887. */
  23888. this.useConstantAnimationDeltaTime = false;
  23889. /**
  23890. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23891. * Please note that it requires to run a ray cast through the scene on every frame
  23892. */
  23893. this.constantlyUpdateMeshUnderPointer = false;
  23894. /**
  23895. * Defines the HTML cursor to use when hovering over interactive elements
  23896. */
  23897. this.hoverCursor = "pointer";
  23898. /**
  23899. * Defines the HTML default cursor to use (empty by default)
  23900. */
  23901. this.defaultCursor = "";
  23902. /**
  23903. * This is used to call preventDefault() on pointer down
  23904. * in order to block unwanted artifacts like system double clicks
  23905. */
  23906. this.preventDefaultOnPointerDown = true;
  23907. // Metadata
  23908. /**
  23909. * Gets or sets user defined metadata
  23910. */
  23911. this.metadata = null;
  23912. /**
  23913. * Use this array to add regular expressions used to disable offline support for specific urls
  23914. */
  23915. this.disableOfflineSupportExceptionRules = new Array();
  23916. /**
  23917. * An event triggered when the scene is disposed.
  23918. */
  23919. this.onDisposeObservable = new BABYLON.Observable();
  23920. this._onDisposeObserver = null;
  23921. /**
  23922. * An event triggered before rendering the scene (right after animations and physics)
  23923. */
  23924. this.onBeforeRenderObservable = new BABYLON.Observable();
  23925. this._onBeforeRenderObserver = null;
  23926. /**
  23927. * An event triggered after rendering the scene
  23928. */
  23929. this.onAfterRenderObservable = new BABYLON.Observable();
  23930. this._onAfterRenderObserver = null;
  23931. /**
  23932. * An event triggered before animating the scene
  23933. */
  23934. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23935. /**
  23936. * An event triggered after animations processing
  23937. */
  23938. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23939. /**
  23940. * An event triggered before draw calls are ready to be sent
  23941. */
  23942. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23943. /**
  23944. * An event triggered after draw calls have been sent
  23945. */
  23946. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23947. /**
  23948. * An event triggered when physic simulation is about to be run
  23949. */
  23950. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered when physic simulation has been done
  23953. */
  23954. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23955. /**
  23956. * An event triggered when the scene is ready
  23957. */
  23958. this.onReadyObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered before rendering a camera
  23961. */
  23962. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23963. this._onBeforeCameraRenderObserver = null;
  23964. /**
  23965. * An event triggered after rendering a camera
  23966. */
  23967. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23968. this._onAfterCameraRenderObserver = null;
  23969. /**
  23970. * An event triggered when active meshes evaluation is about to start
  23971. */
  23972. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23973. /**
  23974. * An event triggered when active meshes evaluation is done
  23975. */
  23976. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23977. /**
  23978. * An event triggered when particles rendering is about to start
  23979. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23980. */
  23981. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23982. /**
  23983. * An event triggered when particles rendering is done
  23984. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23985. */
  23986. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered when sprites rendering is about to start
  23989. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23990. */
  23991. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23992. /**
  23993. * An event triggered when sprites rendering is done
  23994. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23995. */
  23996. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23997. /**
  23998. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23999. */
  24000. this.onDataLoadedObservable = new BABYLON.Observable();
  24001. /**
  24002. * An event triggered when a camera is created
  24003. */
  24004. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24005. /**
  24006. * An event triggered when a camera is removed
  24007. */
  24008. this.onCameraRemovedObservable = new BABYLON.Observable();
  24009. /**
  24010. * An event triggered when a light is created
  24011. */
  24012. this.onNewLightAddedObservable = new BABYLON.Observable();
  24013. /**
  24014. * An event triggered when a light is removed
  24015. */
  24016. this.onLightRemovedObservable = new BABYLON.Observable();
  24017. /**
  24018. * An event triggered when a geometry is created
  24019. */
  24020. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24021. /**
  24022. * An event triggered when a geometry is removed
  24023. */
  24024. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24025. /**
  24026. * An event triggered when a transform node is created
  24027. */
  24028. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when a transform node is removed
  24031. */
  24032. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when a mesh is created
  24035. */
  24036. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when a mesh is removed
  24039. */
  24040. this.onMeshRemovedObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when render targets are about to be rendered
  24043. * Can happen multiple times per frame.
  24044. */
  24045. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when render targets were rendered.
  24048. * Can happen multiple times per frame.
  24049. */
  24050. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24051. /**
  24052. * An event triggered before calculating deterministic simulation step
  24053. */
  24054. this.onBeforeStepObservable = new BABYLON.Observable();
  24055. /**
  24056. * An event triggered after calculating deterministic simulation step
  24057. */
  24058. this.onAfterStepObservable = new BABYLON.Observable();
  24059. /**
  24060. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24061. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24062. * 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)
  24063. */
  24064. this.onRenderingGroupObservable = new BABYLON.Observable();
  24065. // Animations
  24066. /**
  24067. * Gets a list of Animations associated with the scene
  24068. */
  24069. this.animations = [];
  24070. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24071. /**
  24072. * 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).
  24073. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24074. */
  24075. this.onPrePointerObservable = new BABYLON.Observable();
  24076. /**
  24077. * Observable event triggered each time an input event is received from the rendering canvas
  24078. */
  24079. this.onPointerObservable = new BABYLON.Observable();
  24080. this._meshPickProceed = false;
  24081. this._currentPickResult = null;
  24082. this._previousPickResult = null;
  24083. this._totalPointersPressed = 0;
  24084. this._doubleClickOccured = false;
  24085. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24086. this.cameraToUseForPointers = null;
  24087. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24088. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24089. this._startingPointerTime = 0;
  24090. this._previousStartingPointerTime = 0;
  24091. this._pointerCaptures = {};
  24092. // Deterministic lockstep
  24093. this._timeAccumulator = 0;
  24094. this._currentStepId = 0;
  24095. this._currentInternalStep = 0;
  24096. // Keyboard
  24097. /**
  24098. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24099. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24100. */
  24101. this.onPreKeyboardObservable = new BABYLON.Observable();
  24102. /**
  24103. * Observable event triggered each time an keyboard event is received from the hosting window
  24104. */
  24105. this.onKeyboardObservable = new BABYLON.Observable();
  24106. // Coordinates system
  24107. this._useRightHandedSystem = false;
  24108. // Fog
  24109. this._fogEnabled = true;
  24110. this._fogMode = Scene.FOGMODE_NONE;
  24111. /**
  24112. * Gets or sets the fog color to use
  24113. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24114. */
  24115. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24116. /**
  24117. * Gets or sets the fog density to use
  24118. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24119. */
  24120. this.fogDensity = 0.1;
  24121. /**
  24122. * Gets or sets the fog start distance to use
  24123. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24124. */
  24125. this.fogStart = 0;
  24126. /**
  24127. * Gets or sets the fog end distance to use
  24128. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24129. */
  24130. this.fogEnd = 1000.0;
  24131. // Lights
  24132. this._shadowsEnabled = true;
  24133. this._lightsEnabled = true;
  24134. /**
  24135. * All of the lights added to this scene
  24136. * @see http://doc.babylonjs.com/babylon101/lights
  24137. */
  24138. this.lights = new Array();
  24139. // Cameras
  24140. /** All of the cameras added to this scene.
  24141. * @see http://doc.babylonjs.com/babylon101/cameras
  24142. */
  24143. this.cameras = new Array();
  24144. /** All of the active cameras added to this scene. */
  24145. this.activeCameras = new Array();
  24146. // Meshes
  24147. /**
  24148. * All of the tranform nodes added to this scene
  24149. * @see http://doc.babylonjs.com/how_to/transformnode
  24150. */
  24151. this.transformNodes = new Array();
  24152. /**
  24153. * All of the (abstract) meshes added to this scene
  24154. */
  24155. this.meshes = new Array();
  24156. /**
  24157. * All of the animation groups added to this scene
  24158. * @see http://doc.babylonjs.com/how_to/group
  24159. */
  24160. this.animationGroups = new Array();
  24161. // Geometries
  24162. this._geometries = new Array();
  24163. /**
  24164. * All of the materials added to this scene
  24165. * @see http://doc.babylonjs.com/babylon101/materials
  24166. */
  24167. this.materials = new Array();
  24168. /**
  24169. * All of the multi-materials added to this scene
  24170. * @see http://doc.babylonjs.com/how_to/multi_materials
  24171. */
  24172. this.multiMaterials = new Array();
  24173. // Textures
  24174. this._texturesEnabled = true;
  24175. /**
  24176. * All of the textures added to this scene
  24177. */
  24178. this.textures = new Array();
  24179. // Particles
  24180. /**
  24181. * Gets or sets a boolean indicating if particles are enabled on this scene
  24182. */
  24183. this.particlesEnabled = true;
  24184. /**
  24185. * All of the particle systems added to this scene
  24186. * @see http://doc.babylonjs.com/babylon101/particles
  24187. */
  24188. this.particleSystems = new Array();
  24189. // Sprites
  24190. /**
  24191. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24192. */
  24193. this.spritesEnabled = true;
  24194. /**
  24195. * All of the sprite managers added to this scene
  24196. * @see http://doc.babylonjs.com/babylon101/sprites
  24197. */
  24198. this.spriteManagers = new Array();
  24199. /**
  24200. * The list of layers (background and foreground) of the scene
  24201. */
  24202. this.layers = new Array();
  24203. /**
  24204. * The list of effect layers (highlights/glow) added to the scene
  24205. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24206. * @see http://doc.babylonjs.com/how_to/glow_layer
  24207. */
  24208. this.effectLayers = new Array();
  24209. // Skeletons
  24210. this._skeletonsEnabled = true;
  24211. /**
  24212. * The list of skeletons added to the scene
  24213. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24214. */
  24215. this.skeletons = new Array();
  24216. // Morph targets
  24217. /**
  24218. * The list of morph target managers added to the scene
  24219. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24220. */
  24221. this.morphTargetManagers = new Array();
  24222. // Lens flares
  24223. /**
  24224. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24225. */
  24226. this.lensFlaresEnabled = true;
  24227. /**
  24228. * The list of lens flare system added to the scene
  24229. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24230. */
  24231. this.lensFlareSystems = new Array();
  24232. // Collisions
  24233. /**
  24234. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24235. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24236. */
  24237. this.collisionsEnabled = true;
  24238. /**
  24239. * Defines the gravity applied to this scene (used only for collisions)
  24240. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24241. */
  24242. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24243. // Postprocesses
  24244. /**
  24245. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24246. */
  24247. this.postProcessesEnabled = true;
  24248. /**
  24249. * The list of postprocesses added to the scene
  24250. */
  24251. this.postProcesses = new Array();
  24252. // Customs render targets
  24253. /**
  24254. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24255. */
  24256. this.renderTargetsEnabled = true;
  24257. /**
  24258. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24259. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24260. */
  24261. this.dumpNextRenderTargets = false;
  24262. /**
  24263. * The list of user defined render targets added to the scene
  24264. */
  24265. this.customRenderTargets = new Array();
  24266. /**
  24267. * Gets the list of meshes imported to the scene through SceneLoader
  24268. */
  24269. this.importedMeshesFiles = new Array();
  24270. // Probes
  24271. /**
  24272. * Gets or sets a boolean indicating if probes are enabled on this scene
  24273. */
  24274. this.probesEnabled = true;
  24275. /**
  24276. * The list of reflection probes added to the scene
  24277. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24278. */
  24279. this.reflectionProbes = new Array();
  24280. /** @hidden */
  24281. this._actionManagers = new Array();
  24282. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24283. // Procedural textures
  24284. /**
  24285. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24286. */
  24287. this.proceduralTexturesEnabled = true;
  24288. /**
  24289. * The list of procedural textures added to the scene
  24290. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24291. */
  24292. this.proceduralTextures = new Array();
  24293. /**
  24294. * The list of sound tracks added to the scene
  24295. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24296. */
  24297. this.soundTracks = new Array();
  24298. this._audioEnabled = true;
  24299. this._headphone = false;
  24300. // Performance counters
  24301. this._totalVertices = new BABYLON.PerfCounter();
  24302. /** @hidden */
  24303. this._activeIndices = new BABYLON.PerfCounter();
  24304. /** @hidden */
  24305. this._activeParticles = new BABYLON.PerfCounter();
  24306. /** @hidden */
  24307. this._activeBones = new BABYLON.PerfCounter();
  24308. this._animationTime = 0;
  24309. /**
  24310. * Gets or sets a general scale for animation speed
  24311. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24312. */
  24313. this.animationTimeScale = 1;
  24314. this._renderId = 0;
  24315. this._executeWhenReadyTimeoutId = -1;
  24316. this._intermediateRendering = false;
  24317. this._viewUpdateFlag = -1;
  24318. this._projectionUpdateFlag = -1;
  24319. this._alternateViewUpdateFlag = -1;
  24320. this._alternateProjectionUpdateFlag = -1;
  24321. /** @hidden */
  24322. this._toBeDisposed = new BABYLON.SmartArray(256);
  24323. this._activeRequests = new Array();
  24324. this._pendingData = new Array();
  24325. this._isDisposed = false;
  24326. /**
  24327. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24328. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24329. */
  24330. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24331. this._activeMeshes = new BABYLON.SmartArray(256);
  24332. this._processedMaterials = new BABYLON.SmartArray(256);
  24333. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24334. /** @hidden */
  24335. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24336. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24337. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24338. /** @hidden */
  24339. this._activeAnimatables = new Array();
  24340. this._transformMatrix = BABYLON.Matrix.Zero();
  24341. this._useAlternateCameraConfiguration = false;
  24342. this._alternateRendering = false;
  24343. /**
  24344. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24345. * This is useful if there are more lights that the maximum simulteanous authorized
  24346. */
  24347. this.requireLightSorting = false;
  24348. this._depthRenderer = {};
  24349. this._activeMeshesFrozen = false;
  24350. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24351. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24352. this._engine.scenes.push(this);
  24353. this._uid = null;
  24354. this._renderingManager = new BABYLON.RenderingManager(this);
  24355. if (BABYLON.PostProcessManager) {
  24356. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24357. }
  24358. if (BABYLON.OutlineRenderer) {
  24359. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24360. }
  24361. if (BABYLON.Tools.IsWindowObjectExist()) {
  24362. this.attachControl();
  24363. }
  24364. //simplification queue
  24365. if (BABYLON.SimplificationQueue) {
  24366. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24367. }
  24368. //collision coordinator initialization. For now legacy per default.
  24369. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24370. // Uniform Buffer
  24371. this._createUbo();
  24372. // Default Image processing definition
  24373. if (BABYLON.ImageProcessingConfiguration) {
  24374. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24375. }
  24376. }
  24377. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24378. /** The fog is deactivated */
  24379. get: function () {
  24380. return Scene._FOGMODE_NONE;
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24386. /** The fog density is following an exponential function */
  24387. get: function () {
  24388. return Scene._FOGMODE_EXP;
  24389. },
  24390. enumerable: true,
  24391. configurable: true
  24392. });
  24393. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24394. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24395. get: function () {
  24396. return Scene._FOGMODE_EXP2;
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24402. /** The fog density is following a linear function. */
  24403. get: function () {
  24404. return Scene._FOGMODE_LINEAR;
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  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, "gamepadManager", {
  24555. /**
  24556. * Gets the gamepad manager associated with the scene
  24557. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24558. */
  24559. get: function () {
  24560. if (!this._gamepadManager) {
  24561. this._gamepadManager = new BABYLON.GamepadManager(this);
  24562. }
  24563. return this._gamepadManager;
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24569. /**
  24570. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24571. */
  24572. get: function () {
  24573. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24579. get: function () {
  24580. return this._useRightHandedSystem;
  24581. },
  24582. /**
  24583. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24584. */
  24585. set: function (value) {
  24586. if (this._useRightHandedSystem === value) {
  24587. return;
  24588. }
  24589. this._useRightHandedSystem = value;
  24590. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24591. },
  24592. enumerable: true,
  24593. configurable: true
  24594. });
  24595. /**
  24596. * Sets the step Id used by deterministic lock step
  24597. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24598. * @param newStepId defines the step Id
  24599. */
  24600. Scene.prototype.setStepId = function (newStepId) {
  24601. this._currentStepId = newStepId;
  24602. };
  24603. ;
  24604. /**
  24605. * Gets the step Id used by deterministic lock step
  24606. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24607. * @returns the step Id
  24608. */
  24609. Scene.prototype.getStepId = function () {
  24610. return this._currentStepId;
  24611. };
  24612. ;
  24613. /**
  24614. * Gets the internal step used by deterministic lock step
  24615. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24616. * @returns the internal step
  24617. */
  24618. Scene.prototype.getInternalStep = function () {
  24619. return this._currentInternalStep;
  24620. };
  24621. ;
  24622. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24623. get: function () {
  24624. return this._fogEnabled;
  24625. },
  24626. /**
  24627. * Gets or sets a boolean indicating if fog is enabled on this scene
  24628. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24629. */
  24630. set: function (value) {
  24631. if (this._fogEnabled === value) {
  24632. return;
  24633. }
  24634. this._fogEnabled = value;
  24635. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24636. },
  24637. enumerable: true,
  24638. configurable: true
  24639. });
  24640. Object.defineProperty(Scene.prototype, "fogMode", {
  24641. get: function () {
  24642. return this._fogMode;
  24643. },
  24644. /**
  24645. * Gets or sets the fog mode to use
  24646. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24647. */
  24648. set: function (value) {
  24649. if (this._fogMode === value) {
  24650. return;
  24651. }
  24652. this._fogMode = value;
  24653. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24654. },
  24655. enumerable: true,
  24656. configurable: true
  24657. });
  24658. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24659. get: function () {
  24660. return this._shadowsEnabled;
  24661. },
  24662. /**
  24663. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24664. */
  24665. set: function (value) {
  24666. if (this._shadowsEnabled === value) {
  24667. return;
  24668. }
  24669. this._shadowsEnabled = value;
  24670. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24676. get: function () {
  24677. return this._lightsEnabled;
  24678. },
  24679. /**
  24680. * Gets or sets a boolean indicating if lights are enabled on this scene
  24681. */
  24682. set: function (value) {
  24683. if (this._lightsEnabled === value) {
  24684. return;
  24685. }
  24686. this._lightsEnabled = value;
  24687. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24693. /** The default material used on meshes when no material is affected */
  24694. get: function () {
  24695. if (!this._defaultMaterial) {
  24696. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24697. }
  24698. return this._defaultMaterial;
  24699. },
  24700. /** The default material used on meshes when no material is affected */
  24701. set: function (value) {
  24702. this._defaultMaterial = value;
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24708. get: function () {
  24709. return this._texturesEnabled;
  24710. },
  24711. /**
  24712. * Gets or sets a boolean indicating if textures are enabled on this scene
  24713. */
  24714. set: function (value) {
  24715. if (this._texturesEnabled === value) {
  24716. return;
  24717. }
  24718. this._texturesEnabled = value;
  24719. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24725. get: function () {
  24726. return this._skeletonsEnabled;
  24727. },
  24728. /**
  24729. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24730. */
  24731. set: function (value) {
  24732. if (this._skeletonsEnabled === value) {
  24733. return;
  24734. }
  24735. this._skeletonsEnabled = value;
  24736. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24737. },
  24738. enumerable: true,
  24739. configurable: true
  24740. });
  24741. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24742. /**
  24743. * Gets the postprocess render pipeline manager
  24744. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24745. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24746. */
  24747. get: function () {
  24748. if (!this._postProcessRenderPipelineManager) {
  24749. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24750. }
  24751. return this._postProcessRenderPipelineManager;
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24757. /**
  24758. * Gets the main soundtrack associated with the scene
  24759. */
  24760. get: function () {
  24761. if (!this._mainSoundTrack) {
  24762. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24763. }
  24764. return this._mainSoundTrack;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24770. /** @hidden */
  24771. get: function () {
  24772. return this._alternateRendering;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24778. /**
  24779. * Gets the list of frustum planes (built from the active camera)
  24780. */
  24781. get: function () {
  24782. return this._frustumPlanes;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24788. /**
  24789. * Gets the current geometry buffer associated to the scene.
  24790. */
  24791. get: function () {
  24792. return this._geometryBufferRenderer;
  24793. },
  24794. /**
  24795. * Sets the current geometry buffer for the scene.
  24796. */
  24797. set: function (geometryBufferRenderer) {
  24798. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24799. this._geometryBufferRenderer = geometryBufferRenderer;
  24800. }
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. Object.defineProperty(Scene.prototype, "debugLayer", {
  24806. /**
  24807. * Gets the debug layer (aka Inspector) associated with the scene
  24808. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24809. */
  24810. get: function () {
  24811. if (!this._debugLayer) {
  24812. this._debugLayer = new BABYLON.DebugLayer(this);
  24813. }
  24814. return this._debugLayer;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24820. /**
  24821. * Gets a boolean indicating if collisions are processed on a web worker
  24822. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24823. */
  24824. get: function () {
  24825. return this._workerCollisions;
  24826. },
  24827. set: function (enabled) {
  24828. if (!BABYLON.CollisionCoordinatorLegacy) {
  24829. return;
  24830. }
  24831. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24832. this._workerCollisions = enabled;
  24833. if (this.collisionCoordinator) {
  24834. this.collisionCoordinator.destroy();
  24835. }
  24836. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24837. this.collisionCoordinator.init(this);
  24838. },
  24839. enumerable: true,
  24840. configurable: true
  24841. });
  24842. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24843. /**
  24844. * Gets the octree used to boost mesh selection (picking)
  24845. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24846. */
  24847. get: function () {
  24848. return this._selectionOctree;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24854. /**
  24855. * Gets the mesh that is currently under the pointer
  24856. */
  24857. get: function () {
  24858. return this._pointerOverMesh;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Scene.prototype, "pointerX", {
  24864. /**
  24865. * Gets the current on-screen X position of the pointer
  24866. */
  24867. get: function () {
  24868. return this._pointerX;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Scene.prototype, "pointerY", {
  24874. /**
  24875. * Gets the current on-screen Y position of the pointer
  24876. */
  24877. get: function () {
  24878. return this._pointerY;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. /**
  24884. * Gets the cached material (ie. the latest rendered one)
  24885. * @returns the cached material
  24886. */
  24887. Scene.prototype.getCachedMaterial = function () {
  24888. return this._cachedMaterial;
  24889. };
  24890. /**
  24891. * Gets the cached effect (ie. the latest rendered one)
  24892. * @returns the cached effect
  24893. */
  24894. Scene.prototype.getCachedEffect = function () {
  24895. return this._cachedEffect;
  24896. };
  24897. /**
  24898. * Gets the cached visibility state (ie. the latest rendered one)
  24899. * @returns the cached visibility state
  24900. */
  24901. Scene.prototype.getCachedVisibility = function () {
  24902. return this._cachedVisibility;
  24903. };
  24904. /**
  24905. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24906. * @param material defines the current material
  24907. * @param effect defines the current effect
  24908. * @param visibility defines the current visibility state
  24909. * @returns true if one parameter is not cached
  24910. */
  24911. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24912. if (visibility === void 0) { visibility = 1; }
  24913. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24914. };
  24915. /**
  24916. * Gets the bounding box renderer associated with the scene
  24917. * @returns a BoundingBoxRenderer
  24918. */
  24919. Scene.prototype.getBoundingBoxRenderer = function () {
  24920. if (!this._boundingBoxRenderer) {
  24921. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24922. }
  24923. return this._boundingBoxRenderer;
  24924. };
  24925. /**
  24926. * Gets the outline renderer associated with the scene
  24927. * @returns a OutlineRenderer
  24928. */
  24929. Scene.prototype.getOutlineRenderer = function () {
  24930. return this._outlineRenderer;
  24931. };
  24932. /**
  24933. * Gets the engine associated with the scene
  24934. * @returns an Engine
  24935. */
  24936. Scene.prototype.getEngine = function () {
  24937. return this._engine;
  24938. };
  24939. /**
  24940. * Gets the total number of vertices rendered per frame
  24941. * @returns the total number of vertices rendered per frame
  24942. */
  24943. Scene.prototype.getTotalVertices = function () {
  24944. return this._totalVertices.current;
  24945. };
  24946. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24947. /**
  24948. * Gets the performance counter for total vertices
  24949. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24950. */
  24951. get: function () {
  24952. return this._totalVertices;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. /**
  24958. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24959. * @returns the total number of active indices rendered per frame
  24960. */
  24961. Scene.prototype.getActiveIndices = function () {
  24962. return this._activeIndices.current;
  24963. };
  24964. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24965. /**
  24966. * Gets the performance counter for active indices
  24967. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24968. */
  24969. get: function () {
  24970. return this._activeIndices;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. /**
  24976. * Gets the total number of active particles rendered per frame
  24977. * @returns the total number of active particles rendered per frame
  24978. */
  24979. Scene.prototype.getActiveParticles = function () {
  24980. return this._activeParticles.current;
  24981. };
  24982. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24983. /**
  24984. * Gets the performance counter for active particles
  24985. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24986. */
  24987. get: function () {
  24988. return this._activeParticles;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. /**
  24994. * Gets the total number of active bones rendered per frame
  24995. * @returns the total number of active bones rendered per frame
  24996. */
  24997. Scene.prototype.getActiveBones = function () {
  24998. return this._activeBones.current;
  24999. };
  25000. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25001. /**
  25002. * Gets the performance counter for active bones
  25003. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25004. */
  25005. get: function () {
  25006. return this._activeBones;
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. /** @hidden */
  25012. Scene.prototype.getInterFramePerfCounter = function () {
  25013. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25014. return 0;
  25015. };
  25016. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25017. /** @hidden */
  25018. get: function () {
  25019. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25020. return null;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. /** @hidden */
  25026. Scene.prototype.getLastFrameDuration = function () {
  25027. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25028. return 0;
  25029. };
  25030. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25031. /** @hidden */
  25032. get: function () {
  25033. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25034. return null;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. /** @hidden */
  25040. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25041. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25042. return 0;
  25043. };
  25044. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25045. /** @hidden */
  25046. get: function () {
  25047. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25048. return null;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. /**
  25054. * Gets the array of active meshes
  25055. * @returns an array of AbstractMesh
  25056. */
  25057. Scene.prototype.getActiveMeshes = function () {
  25058. return this._activeMeshes;
  25059. };
  25060. /** @hidden */
  25061. Scene.prototype.getRenderTargetsDuration = function () {
  25062. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25063. return 0;
  25064. };
  25065. /** @hidden */
  25066. Scene.prototype.getRenderDuration = function () {
  25067. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25068. return 0;
  25069. };
  25070. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25071. /** @hidden */
  25072. get: function () {
  25073. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25074. return null;
  25075. },
  25076. enumerable: true,
  25077. configurable: true
  25078. });
  25079. /** @hidden */
  25080. Scene.prototype.getParticlesDuration = function () {
  25081. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25082. return 0;
  25083. };
  25084. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25085. /** @hidden */
  25086. get: function () {
  25087. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25088. return null;
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. /** @hidden */
  25094. Scene.prototype.getSpritesDuration = function () {
  25095. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25096. return 0;
  25097. };
  25098. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25099. /** @hidden */
  25100. get: function () {
  25101. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25102. return null;
  25103. },
  25104. enumerable: true,
  25105. configurable: true
  25106. });
  25107. /**
  25108. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25109. * @returns a number
  25110. */
  25111. Scene.prototype.getAnimationRatio = function () {
  25112. return this._animationRatio;
  25113. };
  25114. /**
  25115. * Gets an unique Id for the current frame
  25116. * @returns a number
  25117. */
  25118. Scene.prototype.getRenderId = function () {
  25119. return this._renderId;
  25120. };
  25121. /** Call this function if you want to manually increment the render Id*/
  25122. Scene.prototype.incrementRenderId = function () {
  25123. this._renderId++;
  25124. };
  25125. Scene.prototype._updatePointerPosition = function (evt) {
  25126. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25127. if (!canvasRect) {
  25128. return;
  25129. }
  25130. this._pointerX = evt.clientX - canvasRect.left;
  25131. this._pointerY = evt.clientY - canvasRect.top;
  25132. this._unTranslatedPointerX = this._pointerX;
  25133. this._unTranslatedPointerY = this._pointerY;
  25134. };
  25135. Scene.prototype._createUbo = function () {
  25136. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25137. this._sceneUbo.addUniform("viewProjection", 16);
  25138. this._sceneUbo.addUniform("view", 16);
  25139. };
  25140. Scene.prototype._createAlternateUbo = function () {
  25141. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25142. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25143. this._alternateSceneUbo.addUniform("view", 16);
  25144. };
  25145. // Pointers handling
  25146. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25147. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25148. if (result) {
  25149. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25150. }
  25151. return result;
  25152. };
  25153. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25154. if (pointerInfo.pickInfo) {
  25155. if (!pointerInfo.pickInfo.ray) {
  25156. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25157. }
  25158. }
  25159. };
  25160. /**
  25161. * Use this method to simulate a pointer move on a mesh
  25162. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25163. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25164. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25165. * @returns the current scene
  25166. */
  25167. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25168. var evt = new PointerEvent("pointermove", pointerEventInit);
  25169. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25170. return this;
  25171. }
  25172. return this._processPointerMove(pickResult, evt);
  25173. };
  25174. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25175. var canvas = this._engine.getRenderingCanvas();
  25176. if (!canvas) {
  25177. return this;
  25178. }
  25179. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25180. this.setPointerOverSprite(null);
  25181. this.setPointerOverMesh(pickResult.pickedMesh);
  25182. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25183. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25184. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25185. }
  25186. else {
  25187. canvas.style.cursor = this.hoverCursor;
  25188. }
  25189. }
  25190. else {
  25191. canvas.style.cursor = this.defaultCursor;
  25192. }
  25193. }
  25194. else {
  25195. this.setPointerOverMesh(null);
  25196. // Sprites
  25197. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25198. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25199. this.setPointerOverSprite(pickResult.pickedSprite);
  25200. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25201. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25202. }
  25203. else {
  25204. canvas.style.cursor = this.hoverCursor;
  25205. }
  25206. }
  25207. else {
  25208. this.setPointerOverSprite(null);
  25209. // Restore pointer
  25210. canvas.style.cursor = this.defaultCursor;
  25211. }
  25212. }
  25213. if (pickResult) {
  25214. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25215. if (this.onPointerMove) {
  25216. this.onPointerMove(evt, pickResult, type);
  25217. }
  25218. if (this.onPointerObservable.hasObservers()) {
  25219. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25220. this._setRayOnPointerInfo(pi);
  25221. this.onPointerObservable.notifyObservers(pi, type);
  25222. }
  25223. }
  25224. return this;
  25225. };
  25226. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25227. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25228. if (pickResult) {
  25229. pi.ray = pickResult.ray;
  25230. }
  25231. this.onPrePointerObservable.notifyObservers(pi, type);
  25232. if (pi.skipOnPointerObservable) {
  25233. return true;
  25234. }
  25235. else {
  25236. return false;
  25237. }
  25238. };
  25239. /**
  25240. * Use this method to simulate a pointer down on a mesh
  25241. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25242. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25243. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25244. * @returns the current scene
  25245. */
  25246. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25247. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25248. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25249. return this;
  25250. }
  25251. return this._processPointerDown(pickResult, evt);
  25252. };
  25253. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25254. var _this = this;
  25255. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25256. this._pickedDownMesh = pickResult.pickedMesh;
  25257. var actionManager = pickResult.pickedMesh.actionManager;
  25258. if (actionManager) {
  25259. if (actionManager.hasPickTriggers) {
  25260. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25261. switch (evt.button) {
  25262. case 0:
  25263. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25264. break;
  25265. case 1:
  25266. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25267. break;
  25268. case 2:
  25269. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25270. break;
  25271. }
  25272. }
  25273. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25274. window.setTimeout(function () {
  25275. 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);
  25276. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25277. if (_this._totalPointersPressed !== 0 &&
  25278. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25279. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25280. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25281. _this._startingPointerTime = 0;
  25282. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25283. }
  25284. }
  25285. }, Scene.LongPressDelay);
  25286. }
  25287. }
  25288. }
  25289. if (pickResult) {
  25290. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25291. if (this.onPointerDown) {
  25292. this.onPointerDown(evt, pickResult, type);
  25293. }
  25294. if (this.onPointerObservable.hasObservers()) {
  25295. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25296. this._setRayOnPointerInfo(pi);
  25297. this.onPointerObservable.notifyObservers(pi, type);
  25298. }
  25299. }
  25300. return this;
  25301. };
  25302. /**
  25303. * Use this method to simulate a pointer up on a mesh
  25304. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25305. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25306. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25307. * @returns the current scene
  25308. */
  25309. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25310. var evt = new PointerEvent("pointerup", pointerEventInit);
  25311. var clickInfo = new ClickInfo();
  25312. clickInfo.singleClick = true;
  25313. clickInfo.ignore = true;
  25314. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25315. return this;
  25316. }
  25317. return this._processPointerUp(pickResult, evt, clickInfo);
  25318. };
  25319. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25320. if (pickResult && pickResult && pickResult.pickedMesh) {
  25321. this._pickedUpMesh = pickResult.pickedMesh;
  25322. if (this._pickedDownMesh === this._pickedUpMesh) {
  25323. if (this.onPointerPick) {
  25324. this.onPointerPick(evt, pickResult);
  25325. }
  25326. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25327. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25328. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25329. this._setRayOnPointerInfo(pi);
  25330. this.onPointerObservable.notifyObservers(pi, type_1);
  25331. }
  25332. }
  25333. if (pickResult.pickedMesh.actionManager) {
  25334. if (clickInfo.ignore) {
  25335. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25336. }
  25337. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25338. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25339. }
  25340. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25341. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25342. }
  25343. }
  25344. }
  25345. if (this._pickedDownMesh &&
  25346. this._pickedDownMesh.actionManager &&
  25347. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25348. this._pickedDownMesh !== this._pickedUpMesh) {
  25349. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25350. }
  25351. var type = BABYLON.PointerEventTypes.POINTERUP;
  25352. if (this.onPointerObservable.hasObservers()) {
  25353. if (!clickInfo.ignore) {
  25354. if (!clickInfo.hasSwiped) {
  25355. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25356. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25357. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25358. this._setRayOnPointerInfo(pi);
  25359. this.onPointerObservable.notifyObservers(pi, type_2);
  25360. }
  25361. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25362. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25363. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25364. this._setRayOnPointerInfo(pi);
  25365. this.onPointerObservable.notifyObservers(pi, type_3);
  25366. }
  25367. }
  25368. }
  25369. else {
  25370. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25371. this._setRayOnPointerInfo(pi);
  25372. this.onPointerObservable.notifyObservers(pi, type);
  25373. }
  25374. }
  25375. if (this.onPointerUp) {
  25376. this.onPointerUp(evt, pickResult, type);
  25377. }
  25378. return this;
  25379. };
  25380. /**
  25381. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25382. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25383. * @returns true if the pointer was captured
  25384. */
  25385. Scene.prototype.isPointerCaptured = function (pointerId) {
  25386. if (pointerId === void 0) { pointerId = 0; }
  25387. return this._pointerCaptures[pointerId];
  25388. };
  25389. /**
  25390. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25391. * @param attachUp defines if you want to attach events to pointerup
  25392. * @param attachDown defines if you want to attach events to pointerdown
  25393. * @param attachMove defines if you want to attach events to pointermove
  25394. */
  25395. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25396. var _this = this;
  25397. if (attachUp === void 0) { attachUp = true; }
  25398. if (attachDown === void 0) { attachDown = true; }
  25399. if (attachMove === void 0) { attachMove = true; }
  25400. this._initActionManager = function (act, clickInfo) {
  25401. if (!_this._meshPickProceed) {
  25402. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25403. _this._currentPickResult = pickResult;
  25404. if (pickResult) {
  25405. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25406. }
  25407. _this._meshPickProceed = true;
  25408. }
  25409. return act;
  25410. };
  25411. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25412. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25413. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25414. btn !== _this._previousButtonPressed) {
  25415. _this._doubleClickOccured = false;
  25416. clickInfo.singleClick = true;
  25417. clickInfo.ignore = false;
  25418. cb(clickInfo, _this._currentPickResult);
  25419. }
  25420. };
  25421. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25422. var clickInfo = new ClickInfo();
  25423. _this._currentPickResult = null;
  25424. var act = null;
  25425. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25426. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25427. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25428. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25429. act = _this._initActionManager(act, clickInfo);
  25430. if (act)
  25431. checkPicking = act.hasPickTriggers;
  25432. }
  25433. if (checkPicking) {
  25434. var btn = evt.button;
  25435. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25436. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25437. if (!clickInfo.hasSwiped) {
  25438. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25439. if (!checkSingleClickImmediately) {
  25440. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25441. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25442. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25443. act = _this._initActionManager(act, clickInfo);
  25444. if (act)
  25445. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25446. }
  25447. }
  25448. if (checkSingleClickImmediately) {
  25449. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25450. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25451. btn !== _this._previousButtonPressed) {
  25452. clickInfo.singleClick = true;
  25453. cb(clickInfo, _this._currentPickResult);
  25454. }
  25455. }
  25456. // at least one double click is required to be check and exclusive double click is enabled
  25457. else {
  25458. // wait that no double click has been raised during the double click delay
  25459. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25460. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25461. }
  25462. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25463. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25464. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25465. act = _this._initActionManager(act, clickInfo);
  25466. if (act)
  25467. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25468. }
  25469. if (checkDoubleClick) {
  25470. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25471. if (btn === _this._previousButtonPressed &&
  25472. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25473. !_this._doubleClickOccured) {
  25474. // pointer has not moved for 2 clicks, it's a double click
  25475. if (!clickInfo.hasSwiped &&
  25476. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25477. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25478. _this._previousStartingPointerTime = 0;
  25479. _this._doubleClickOccured = true;
  25480. clickInfo.doubleClick = true;
  25481. clickInfo.ignore = false;
  25482. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25483. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25484. }
  25485. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25486. cb(clickInfo, _this._currentPickResult);
  25487. }
  25488. // if the two successive clicks are too far, it's just two simple clicks
  25489. else {
  25490. _this._doubleClickOccured = false;
  25491. _this._previousStartingPointerTime = _this._startingPointerTime;
  25492. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25493. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25494. _this._previousButtonPressed = btn;
  25495. if (Scene.ExclusiveDoubleClickMode) {
  25496. if (_this._previousDelayedSimpleClickTimeout) {
  25497. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25498. }
  25499. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25500. cb(clickInfo, _this._previousPickResult);
  25501. }
  25502. else {
  25503. cb(clickInfo, _this._currentPickResult);
  25504. }
  25505. }
  25506. }
  25507. // just the first click of the double has been raised
  25508. else {
  25509. _this._doubleClickOccured = false;
  25510. _this._previousStartingPointerTime = _this._startingPointerTime;
  25511. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25512. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25513. _this._previousButtonPressed = btn;
  25514. }
  25515. }
  25516. }
  25517. }
  25518. clickInfo.ignore = true;
  25519. cb(clickInfo, _this._currentPickResult);
  25520. };
  25521. this._spritePredicate = function (sprite) {
  25522. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25523. };
  25524. this._onPointerMove = function (evt) {
  25525. _this._updatePointerPosition(evt);
  25526. // PreObservable support
  25527. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25528. return;
  25529. }
  25530. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25531. return;
  25532. }
  25533. if (!_this.pointerMovePredicate) {
  25534. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25535. }
  25536. // Meshes
  25537. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25538. _this._processPointerMove(pickResult, evt);
  25539. };
  25540. this._onPointerDown = function (evt) {
  25541. _this._totalPointersPressed++;
  25542. _this._pickedDownMesh = null;
  25543. _this._meshPickProceed = false;
  25544. _this._updatePointerPosition(evt);
  25545. if (_this.preventDefaultOnPointerDown && canvas) {
  25546. evt.preventDefault();
  25547. canvas.focus();
  25548. }
  25549. // PreObservable support
  25550. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25551. return;
  25552. }
  25553. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25554. return;
  25555. }
  25556. _this._pointerCaptures[evt.pointerId] = true;
  25557. _this._startingPointerPosition.x = _this._pointerX;
  25558. _this._startingPointerPosition.y = _this._pointerY;
  25559. _this._startingPointerTime = Date.now();
  25560. if (!_this.pointerDownPredicate) {
  25561. _this.pointerDownPredicate = function (mesh) {
  25562. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25563. };
  25564. }
  25565. // Meshes
  25566. _this._pickedDownMesh = null;
  25567. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25568. _this._processPointerDown(pickResult, evt);
  25569. // Sprites
  25570. _this._pickedDownSprite = null;
  25571. if (_this.spriteManagers.length > 0) {
  25572. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25573. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25574. if (pickResult.pickedSprite.actionManager) {
  25575. _this._pickedDownSprite = pickResult.pickedSprite;
  25576. switch (evt.button) {
  25577. case 0:
  25578. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25579. break;
  25580. case 1:
  25581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25582. break;
  25583. case 2:
  25584. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25585. break;
  25586. }
  25587. if (pickResult.pickedSprite.actionManager) {
  25588. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25589. }
  25590. }
  25591. }
  25592. }
  25593. };
  25594. this._onPointerUp = function (evt) {
  25595. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25596. return; // So we need to test it the pointer down was pressed before.
  25597. }
  25598. _this._totalPointersPressed--;
  25599. _this._pickedUpMesh = null;
  25600. _this._meshPickProceed = false;
  25601. _this._updatePointerPosition(evt);
  25602. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25603. // PreObservable support
  25604. if (_this.onPrePointerObservable.hasObservers()) {
  25605. if (!clickInfo.ignore) {
  25606. if (!clickInfo.hasSwiped) {
  25607. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25608. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25609. return;
  25610. }
  25611. }
  25612. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25613. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25614. return;
  25615. }
  25616. }
  25617. }
  25618. }
  25619. else {
  25620. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25621. return;
  25622. }
  25623. }
  25624. }
  25625. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25626. return;
  25627. }
  25628. _this._pointerCaptures[evt.pointerId] = false;
  25629. if (!_this.pointerUpPredicate) {
  25630. _this.pointerUpPredicate = function (mesh) {
  25631. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25632. };
  25633. }
  25634. // Meshes
  25635. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25636. _this._initActionManager(null, clickInfo);
  25637. }
  25638. if (!pickResult) {
  25639. pickResult = _this._currentPickResult;
  25640. }
  25641. _this._processPointerUp(pickResult, evt, clickInfo);
  25642. // Sprites
  25643. if (!clickInfo.ignore) {
  25644. if (_this.spriteManagers.length > 0) {
  25645. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25646. if (spritePickResult) {
  25647. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25648. if (spritePickResult.pickedSprite.actionManager) {
  25649. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25650. if (spritePickResult.pickedSprite.actionManager) {
  25651. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25652. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25653. }
  25654. }
  25655. }
  25656. }
  25657. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25658. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25659. }
  25660. }
  25661. }
  25662. }
  25663. _this._previousPickResult = _this._currentPickResult;
  25664. });
  25665. };
  25666. this._onKeyDown = function (evt) {
  25667. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25668. if (_this.onPreKeyboardObservable.hasObservers()) {
  25669. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25670. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25671. if (pi.skipOnPointerObservable) {
  25672. return;
  25673. }
  25674. }
  25675. if (_this.onKeyboardObservable.hasObservers()) {
  25676. var pi = new BABYLON.KeyboardInfo(type, evt);
  25677. _this.onKeyboardObservable.notifyObservers(pi, type);
  25678. }
  25679. if (_this.actionManager) {
  25680. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25681. }
  25682. };
  25683. this._onKeyUp = function (evt) {
  25684. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25685. if (_this.onPreKeyboardObservable.hasObservers()) {
  25686. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25687. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25688. if (pi.skipOnPointerObservable) {
  25689. return;
  25690. }
  25691. }
  25692. if (_this.onKeyboardObservable.hasObservers()) {
  25693. var pi = new BABYLON.KeyboardInfo(type, evt);
  25694. _this.onKeyboardObservable.notifyObservers(pi, type);
  25695. }
  25696. if (_this.actionManager) {
  25697. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25698. }
  25699. };
  25700. var engine = this.getEngine();
  25701. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25702. if (!canvas) {
  25703. return;
  25704. }
  25705. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25706. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25707. });
  25708. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25709. if (!canvas) {
  25710. return;
  25711. }
  25712. canvas.removeEventListener("keydown", _this._onKeyDown);
  25713. canvas.removeEventListener("keyup", _this._onKeyUp);
  25714. });
  25715. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25716. var canvas = this._engine.getRenderingCanvas();
  25717. if (!canvas) {
  25718. return;
  25719. }
  25720. if (attachMove) {
  25721. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25722. // Wheel
  25723. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25724. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25725. }
  25726. if (attachDown) {
  25727. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25728. }
  25729. if (attachUp) {
  25730. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25731. }
  25732. canvas.tabIndex = 1;
  25733. };
  25734. /** Detaches all event handlers*/
  25735. Scene.prototype.detachControl = function () {
  25736. var engine = this.getEngine();
  25737. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25738. var canvas = engine.getRenderingCanvas();
  25739. if (!canvas) {
  25740. return;
  25741. }
  25742. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25743. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25744. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25745. if (this._onCanvasBlurObserver) {
  25746. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25747. }
  25748. if (this._onCanvasFocusObserver) {
  25749. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25750. }
  25751. // Wheel
  25752. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25753. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25754. // Keyboard
  25755. canvas.removeEventListener("keydown", this._onKeyDown);
  25756. canvas.removeEventListener("keyup", this._onKeyUp);
  25757. // Observables
  25758. this.onKeyboardObservable.clear();
  25759. this.onPreKeyboardObservable.clear();
  25760. this.onPointerObservable.clear();
  25761. this.onPrePointerObservable.clear();
  25762. };
  25763. /**
  25764. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25765. * Delay loaded resources are not taking in account
  25766. * @return true if all required resources are ready
  25767. */
  25768. Scene.prototype.isReady = function () {
  25769. if (this._isDisposed) {
  25770. return false;
  25771. }
  25772. if (this._pendingData.length > 0) {
  25773. return false;
  25774. }
  25775. var index;
  25776. var engine = this.getEngine();
  25777. // Geometries
  25778. for (index = 0; index < this._geometries.length; index++) {
  25779. var geometry = this._geometries[index];
  25780. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25781. return false;
  25782. }
  25783. }
  25784. // Meshes
  25785. for (index = 0; index < this.meshes.length; index++) {
  25786. var mesh = this.meshes[index];
  25787. if (!mesh.isEnabled()) {
  25788. continue;
  25789. }
  25790. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25791. continue;
  25792. }
  25793. if (!mesh.isReady(true)) {
  25794. return false;
  25795. }
  25796. // Effect layers
  25797. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25798. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25799. var layer = _a[_i];
  25800. if (!layer.hasMesh(mesh)) {
  25801. continue;
  25802. }
  25803. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25804. var subMesh = _c[_b];
  25805. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25806. return false;
  25807. }
  25808. }
  25809. }
  25810. }
  25811. // Post-processes
  25812. if (this.activeCameras && this.activeCameras.length > 0) {
  25813. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25814. var camera = _e[_d];
  25815. if (!camera.isReady(true)) {
  25816. return false;
  25817. }
  25818. }
  25819. }
  25820. else if (this.activeCamera) {
  25821. if (!this.activeCamera.isReady(true)) {
  25822. return false;
  25823. }
  25824. }
  25825. // Particles
  25826. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25827. var particleSystem = _g[_f];
  25828. if (!particleSystem.isReady()) {
  25829. return false;
  25830. }
  25831. }
  25832. return true;
  25833. };
  25834. /** Resets all cached information relative to material (including effect and visibility) */
  25835. Scene.prototype.resetCachedMaterial = function () {
  25836. this._cachedMaterial = null;
  25837. this._cachedEffect = null;
  25838. this._cachedVisibility = null;
  25839. };
  25840. /**
  25841. * Registers a function to be called before every frame render
  25842. * @param func defines the function to register
  25843. */
  25844. Scene.prototype.registerBeforeRender = function (func) {
  25845. this.onBeforeRenderObservable.add(func);
  25846. };
  25847. /**
  25848. * Unregisters a function called before every frame render
  25849. * @param func defines the function to unregister
  25850. */
  25851. Scene.prototype.unregisterBeforeRender = function (func) {
  25852. this.onBeforeRenderObservable.removeCallback(func);
  25853. };
  25854. /**
  25855. * Registers a function to be called after every frame render
  25856. * @param func defines the function to register
  25857. */
  25858. Scene.prototype.registerAfterRender = function (func) {
  25859. this.onAfterRenderObservable.add(func);
  25860. };
  25861. /**
  25862. * Unregisters a function called after every frame render
  25863. * @param func defines the function to unregister
  25864. */
  25865. Scene.prototype.unregisterAfterRender = function (func) {
  25866. this.onAfterRenderObservable.removeCallback(func);
  25867. };
  25868. Scene.prototype._executeOnceBeforeRender = function (func) {
  25869. var _this = this;
  25870. var execFunc = function () {
  25871. func();
  25872. setTimeout(function () {
  25873. _this.unregisterBeforeRender(execFunc);
  25874. });
  25875. };
  25876. this.registerBeforeRender(execFunc);
  25877. };
  25878. /**
  25879. * The provided function will run before render once and will be disposed afterwards.
  25880. * A timeout delay can be provided so that the function will be executed in N ms.
  25881. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25882. * @param func The function to be executed.
  25883. * @param timeout optional delay in ms
  25884. */
  25885. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25886. var _this = this;
  25887. if (timeout !== undefined) {
  25888. setTimeout(function () {
  25889. _this._executeOnceBeforeRender(func);
  25890. }, timeout);
  25891. }
  25892. else {
  25893. this._executeOnceBeforeRender(func);
  25894. }
  25895. };
  25896. /** @hidden */
  25897. Scene.prototype._addPendingData = function (data) {
  25898. this._pendingData.push(data);
  25899. };
  25900. /** @hidden */
  25901. Scene.prototype._removePendingData = function (data) {
  25902. var wasLoading = this.isLoading;
  25903. var index = this._pendingData.indexOf(data);
  25904. if (index !== -1) {
  25905. this._pendingData.splice(index, 1);
  25906. }
  25907. if (wasLoading && !this.isLoading) {
  25908. this.onDataLoadedObservable.notifyObservers(this);
  25909. }
  25910. };
  25911. /**
  25912. * Returns the number of items waiting to be loaded
  25913. * @returns the number of items waiting to be loaded
  25914. */
  25915. Scene.prototype.getWaitingItemsCount = function () {
  25916. return this._pendingData.length;
  25917. };
  25918. Object.defineProperty(Scene.prototype, "isLoading", {
  25919. /**
  25920. * Returns a boolean indicating if the scene is still loading data
  25921. */
  25922. get: function () {
  25923. return this._pendingData.length > 0;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. /**
  25929. * Registers a function to be executed when the scene is ready
  25930. * @param {Function} func - the function to be executed
  25931. */
  25932. Scene.prototype.executeWhenReady = function (func) {
  25933. var _this = this;
  25934. this.onReadyObservable.add(func);
  25935. if (this._executeWhenReadyTimeoutId !== -1) {
  25936. return;
  25937. }
  25938. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25939. _this._checkIsReady();
  25940. }, 150);
  25941. };
  25942. /**
  25943. * Returns a promise that resolves when the scene is ready
  25944. * @returns A promise that resolves when the scene is ready
  25945. */
  25946. Scene.prototype.whenReadyAsync = function () {
  25947. var _this = this;
  25948. return new Promise(function (resolve) {
  25949. _this.executeWhenReady(function () {
  25950. resolve();
  25951. });
  25952. });
  25953. };
  25954. /** @hidden */
  25955. Scene.prototype._checkIsReady = function () {
  25956. var _this = this;
  25957. if (this.isReady()) {
  25958. this.onReadyObservable.notifyObservers(this);
  25959. this.onReadyObservable.clear();
  25960. this._executeWhenReadyTimeoutId = -1;
  25961. return;
  25962. }
  25963. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25964. _this._checkIsReady();
  25965. }, 150);
  25966. };
  25967. // Animations
  25968. /**
  25969. * Will start the animation sequence of a given target
  25970. * @param target defines the target
  25971. * @param from defines from which frame should animation start
  25972. * @param to defines until which frame should animation run.
  25973. * @param weight defines the weight to apply to the animation (1.0 by default)
  25974. * @param loop defines if the animation loops
  25975. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25976. * @param onAnimationEnd defines the function to be executed when the animation ends
  25977. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25978. * @returns the animatable object created for this animation
  25979. */
  25980. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25981. if (weight === void 0) { weight = 1.0; }
  25982. if (speedRatio === void 0) { speedRatio = 1.0; }
  25983. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25984. returnedAnimatable.weight = weight;
  25985. return returnedAnimatable;
  25986. };
  25987. /**
  25988. * Will start the animation sequence of a given target
  25989. * @param target defines the target
  25990. * @param from defines from which frame should animation start
  25991. * @param to defines until which frame should animation run.
  25992. * @param loop defines if the animation loops
  25993. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25994. * @param onAnimationEnd defines the function to be executed when the animation ends
  25995. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25996. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25997. * @returns the animatable object created for this animation
  25998. */
  25999. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26000. if (speedRatio === void 0) { speedRatio = 1.0; }
  26001. if (stopCurrent === void 0) { stopCurrent = true; }
  26002. if (from > to && speedRatio > 0) {
  26003. speedRatio *= -1;
  26004. }
  26005. if (stopCurrent) {
  26006. this.stopAnimation(target);
  26007. }
  26008. if (!animatable) {
  26009. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26010. }
  26011. // Local animations
  26012. if (target.animations) {
  26013. animatable.appendAnimations(target, target.animations);
  26014. }
  26015. // Children animations
  26016. if (target.getAnimatables) {
  26017. var animatables = target.getAnimatables();
  26018. for (var index = 0; index < animatables.length; index++) {
  26019. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26020. }
  26021. }
  26022. animatable.reset();
  26023. return animatable;
  26024. };
  26025. /**
  26026. * Begin a new animation on a given node
  26027. * @param target defines the target where the animation will take place
  26028. * @param animations defines the list of animations to start
  26029. * @param from defines the initial value
  26030. * @param to defines the final value
  26031. * @param loop defines if you want animation to loop (off by default)
  26032. * @param speedRatio defines the speed ratio to apply to all animations
  26033. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26034. * @returns the list of created animatables
  26035. */
  26036. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26037. if (speedRatio === undefined) {
  26038. speedRatio = 1.0;
  26039. }
  26040. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26041. return animatable;
  26042. };
  26043. /**
  26044. * Begin a new animation on a given node and its hierarchy
  26045. * @param target defines the root node where the animation will take place
  26046. * @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.
  26047. * @param animations defines the list of animations to start
  26048. * @param from defines the initial value
  26049. * @param to defines the final value
  26050. * @param loop defines if you want animation to loop (off by default)
  26051. * @param speedRatio defines the speed ratio to apply to all animations
  26052. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26053. * @returns the list of animatables created for all nodes
  26054. */
  26055. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26056. var children = target.getDescendants(directDescendantsOnly);
  26057. var result = [];
  26058. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26059. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26060. var child = children_1[_i];
  26061. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26062. }
  26063. return result;
  26064. };
  26065. /**
  26066. * Gets the animatable associated with a specific target
  26067. * @param target defines the target of the animatable
  26068. * @returns the required animatable if found
  26069. */
  26070. Scene.prototype.getAnimatableByTarget = function (target) {
  26071. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26072. if (this._activeAnimatables[index].target === target) {
  26073. return this._activeAnimatables[index];
  26074. }
  26075. }
  26076. return null;
  26077. };
  26078. /**
  26079. * Gets all animatables associated with a given target
  26080. * @param target defines the target to look animatables for
  26081. * @returns an array of Animatables
  26082. */
  26083. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26084. var result = [];
  26085. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26086. if (this._activeAnimatables[index].target === target) {
  26087. result.push(this._activeAnimatables[index]);
  26088. }
  26089. }
  26090. return result;
  26091. };
  26092. Object.defineProperty(Scene.prototype, "animatables", {
  26093. /**
  26094. * Gets all animatable attached to the scene
  26095. */
  26096. get: function () {
  26097. return this._activeAnimatables;
  26098. },
  26099. enumerable: true,
  26100. configurable: true
  26101. });
  26102. /**
  26103. * Will stop the animation of the given target
  26104. * @param target - the target
  26105. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26106. */
  26107. Scene.prototype.stopAnimation = function (target, animationName) {
  26108. var animatables = this.getAllAnimatablesByTarget(target);
  26109. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26110. var animatable = animatables_1[_i];
  26111. animatable.stop(animationName);
  26112. }
  26113. };
  26114. /**
  26115. * Stops and removes all animations that have been applied to the scene
  26116. */
  26117. Scene.prototype.stopAllAnimations = function () {
  26118. if (this._activeAnimatables) {
  26119. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26120. this._activeAnimatables[i].stop();
  26121. }
  26122. this._activeAnimatables = [];
  26123. }
  26124. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26125. var group = _a[_i];
  26126. group.stop();
  26127. }
  26128. };
  26129. Scene.prototype._animate = function () {
  26130. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26131. return;
  26132. }
  26133. // Getting time
  26134. var now = BABYLON.Tools.Now;
  26135. if (!this._animationTimeLast) {
  26136. if (this._pendingData.length > 0) {
  26137. return;
  26138. }
  26139. this._animationTimeLast = now;
  26140. }
  26141. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26142. this._animationTime += deltaTime;
  26143. this._animationTimeLast = now;
  26144. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26145. this._activeAnimatables[index]._animate(this._animationTime);
  26146. }
  26147. // Late animation bindings
  26148. this._processLateAnimationBindings();
  26149. };
  26150. /** @hidden */
  26151. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26152. var target = runtimeAnimation.target;
  26153. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26154. if (!target._lateAnimationHolders) {
  26155. target._lateAnimationHolders = {};
  26156. }
  26157. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26158. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26159. totalWeight: 0,
  26160. animations: [],
  26161. originalValue: originalValue
  26162. };
  26163. }
  26164. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26165. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26166. };
  26167. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26168. var normalizer = 1.0;
  26169. var finalPosition = BABYLON.Tmp.Vector3[0];
  26170. var finalScaling = BABYLON.Tmp.Vector3[1];
  26171. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26172. var startIndex = 0;
  26173. var originalAnimation = holder.animations[0];
  26174. var originalValue = holder.originalValue;
  26175. var scale = 1;
  26176. if (holder.totalWeight < 1.0) {
  26177. // We need to mix the original value in
  26178. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26179. scale = 1.0 - holder.totalWeight;
  26180. }
  26181. else {
  26182. startIndex = 1;
  26183. // We need to normalize the weights
  26184. normalizer = holder.totalWeight;
  26185. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26186. scale = originalAnimation.weight / normalizer;
  26187. if (scale == 1) {
  26188. return originalAnimation.currentValue;
  26189. }
  26190. }
  26191. finalScaling.scaleInPlace(scale);
  26192. finalPosition.scaleInPlace(scale);
  26193. finalQuaternion.scaleInPlace(scale);
  26194. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26195. var runtimeAnimation = holder.animations[animIndex];
  26196. var scale = runtimeAnimation.weight / normalizer;
  26197. var currentPosition = BABYLON.Tmp.Vector3[2];
  26198. var currentScaling = BABYLON.Tmp.Vector3[3];
  26199. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26200. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26201. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26202. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26203. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26204. }
  26205. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26206. return originalAnimation._workValue;
  26207. };
  26208. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26209. var originalAnimation = holder.animations[0];
  26210. var originalValue = holder.originalValue;
  26211. if (holder.animations.length === 1) {
  26212. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26213. }
  26214. var normalizer = 1.0;
  26215. var quaternions;
  26216. var weights;
  26217. if (holder.totalWeight < 1.0) {
  26218. var scale = 1.0 - holder.totalWeight;
  26219. quaternions = [];
  26220. weights = [];
  26221. quaternions.push(originalValue);
  26222. weights.push(scale);
  26223. }
  26224. else {
  26225. if (holder.animations.length === 2) { // Slerp as soon as we can
  26226. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26227. }
  26228. quaternions = [];
  26229. weights = [];
  26230. normalizer = holder.totalWeight;
  26231. }
  26232. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26233. var runtimeAnimation = holder.animations[animIndex];
  26234. quaternions.push(runtimeAnimation.currentValue);
  26235. weights.push(runtimeAnimation.weight / normalizer);
  26236. }
  26237. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26238. var cumulativeAmount = 0;
  26239. var cumulativeQuaternion = null;
  26240. for (var index = 0; index < quaternions.length;) {
  26241. if (!cumulativeQuaternion) {
  26242. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26243. cumulativeAmount = weights[index] + weights[index + 1];
  26244. index += 2;
  26245. continue;
  26246. }
  26247. cumulativeAmount += weights[index];
  26248. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26249. index++;
  26250. }
  26251. return cumulativeQuaternion;
  26252. };
  26253. Scene.prototype._processLateAnimationBindings = function () {
  26254. if (!this._registeredForLateAnimationBindings.length) {
  26255. return;
  26256. }
  26257. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26258. var target = this._registeredForLateAnimationBindings.data[index];
  26259. for (var path in target._lateAnimationHolders) {
  26260. var holder = target._lateAnimationHolders[path];
  26261. var originalAnimation = holder.animations[0];
  26262. var originalValue = holder.originalValue;
  26263. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26264. var finalValue = void 0;
  26265. if (matrixDecomposeMode) {
  26266. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26267. }
  26268. else {
  26269. var quaternionMode = originalValue.w !== undefined;
  26270. if (quaternionMode) {
  26271. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26272. }
  26273. else {
  26274. var startIndex = 0;
  26275. var normalizer = 1.0;
  26276. if (holder.totalWeight < 1.0) {
  26277. // We need to mix the original value in
  26278. if (originalValue.scale) {
  26279. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26280. }
  26281. else {
  26282. finalValue = originalValue * (1.0 - holder.totalWeight);
  26283. }
  26284. }
  26285. else {
  26286. // We need to normalize the weights
  26287. normalizer = holder.totalWeight;
  26288. var scale_1 = originalAnimation.weight / normalizer;
  26289. if (scale_1 !== 1) {
  26290. if (originalAnimation.currentValue.scale) {
  26291. finalValue = originalAnimation.currentValue.scale(scale_1);
  26292. }
  26293. else {
  26294. finalValue = originalAnimation.currentValue * scale_1;
  26295. }
  26296. }
  26297. else {
  26298. finalValue = originalAnimation.currentValue;
  26299. }
  26300. startIndex = 1;
  26301. }
  26302. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26303. var runtimeAnimation = holder.animations[animIndex];
  26304. var scale = runtimeAnimation.weight / normalizer;
  26305. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26306. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26307. }
  26308. else {
  26309. finalValue += runtimeAnimation.currentValue * scale;
  26310. }
  26311. }
  26312. }
  26313. }
  26314. target[path] = finalValue;
  26315. }
  26316. target._lateAnimationHolders = {};
  26317. }
  26318. this._registeredForLateAnimationBindings.reset();
  26319. };
  26320. // Matrix
  26321. /** @hidden */
  26322. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26323. this._useAlternateCameraConfiguration = active;
  26324. };
  26325. /**
  26326. * Gets the current view matrix
  26327. * @returns a Matrix
  26328. */
  26329. Scene.prototype.getViewMatrix = function () {
  26330. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26331. };
  26332. /**
  26333. * Gets the current projection matrix
  26334. * @returns a Matrix
  26335. */
  26336. Scene.prototype.getProjectionMatrix = function () {
  26337. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26338. };
  26339. /**
  26340. * Gets the current transform matrix
  26341. * @returns a Matrix made of View * Projection
  26342. */
  26343. Scene.prototype.getTransformMatrix = function () {
  26344. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26345. };
  26346. /**
  26347. * Sets the current transform matrix
  26348. * @param view defines the View matrix to use
  26349. * @param projection defines the Projection matrix to use
  26350. */
  26351. Scene.prototype.setTransformMatrix = function (view, projection) {
  26352. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26353. return;
  26354. }
  26355. this._viewUpdateFlag = view.updateFlag;
  26356. this._projectionUpdateFlag = projection.updateFlag;
  26357. this._viewMatrix = view;
  26358. this._projectionMatrix = projection;
  26359. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26360. // Update frustum
  26361. if (!this._frustumPlanes) {
  26362. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26363. }
  26364. else {
  26365. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26366. }
  26367. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26368. var otherCamera = this.activeCamera._alternateCamera;
  26369. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26370. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26371. }
  26372. if (this._sceneUbo.useUbo) {
  26373. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26374. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26375. this._sceneUbo.update();
  26376. }
  26377. };
  26378. /** @hidden */
  26379. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26380. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26381. return;
  26382. }
  26383. this._alternateViewUpdateFlag = view.updateFlag;
  26384. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26385. this._alternateViewMatrix = view;
  26386. this._alternateProjectionMatrix = projection;
  26387. if (!this._alternateTransformMatrix) {
  26388. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26389. }
  26390. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26391. if (!this._alternateSceneUbo) {
  26392. this._createAlternateUbo();
  26393. }
  26394. if (this._alternateSceneUbo.useUbo) {
  26395. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26396. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26397. this._alternateSceneUbo.update();
  26398. }
  26399. };
  26400. /**
  26401. * Gets the uniform buffer used to store scene data
  26402. * @returns a UniformBuffer
  26403. */
  26404. Scene.prototype.getSceneUniformBuffer = function () {
  26405. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26406. };
  26407. /**
  26408. * Gets an unique (relatively to the current scene) Id
  26409. * @returns an unique number for the scene
  26410. */
  26411. Scene.prototype.getUniqueId = function () {
  26412. var result = Scene._uniqueIdCounter;
  26413. Scene._uniqueIdCounter++;
  26414. return result;
  26415. };
  26416. /**
  26417. * Add a mesh to the list of scene's meshes
  26418. * @param newMesh defines the mesh to add
  26419. * @param recursive if all child meshes should also be added to the scene
  26420. */
  26421. Scene.prototype.addMesh = function (newMesh, recursive) {
  26422. var _this = this;
  26423. if (recursive === void 0) { recursive = false; }
  26424. this.meshes.push(newMesh);
  26425. //notify the collision coordinator
  26426. if (this.collisionCoordinator) {
  26427. this.collisionCoordinator.onMeshAdded(newMesh);
  26428. }
  26429. newMesh._resyncLightSources();
  26430. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26431. if (recursive) {
  26432. newMesh.getChildMeshes().forEach(function (m) {
  26433. _this.addMesh(m);
  26434. });
  26435. }
  26436. };
  26437. /**
  26438. * Remove a mesh for the list of scene's meshes
  26439. * @param toRemove defines the mesh to remove
  26440. * @param recursive if all child meshes should also be removed from the scene
  26441. * @returns the index where the mesh was in the mesh list
  26442. */
  26443. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26444. var _this = this;
  26445. if (recursive === void 0) { recursive = false; }
  26446. var index = this.meshes.indexOf(toRemove);
  26447. if (index !== -1) {
  26448. // Remove from the scene if mesh found
  26449. this.meshes.splice(index, 1);
  26450. }
  26451. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26452. if (recursive) {
  26453. toRemove.getChildMeshes().forEach(function (m) {
  26454. _this.removeMesh(m);
  26455. });
  26456. }
  26457. return index;
  26458. };
  26459. /**
  26460. * Add a transform node to the list of scene's transform nodes
  26461. * @param newTransformNode defines the transform node to add
  26462. */
  26463. Scene.prototype.addTransformNode = function (newTransformNode) {
  26464. this.transformNodes.push(newTransformNode);
  26465. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26466. };
  26467. /**
  26468. * Remove a transform node for the list of scene's transform nodes
  26469. * @param toRemove defines the transform node to remove
  26470. * @returns the index where the transform node was in the transform node list
  26471. */
  26472. Scene.prototype.removeTransformNode = function (toRemove) {
  26473. var index = this.transformNodes.indexOf(toRemove);
  26474. if (index !== -1) {
  26475. // Remove from the scene if found
  26476. this.transformNodes.splice(index, 1);
  26477. }
  26478. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26479. return index;
  26480. };
  26481. /**
  26482. * Remove a skeleton for the list of scene's skeletons
  26483. * @param toRemove defines the skeleton to remove
  26484. * @returns the index where the skeleton was in the skeleton list
  26485. */
  26486. Scene.prototype.removeSkeleton = function (toRemove) {
  26487. var index = this.skeletons.indexOf(toRemove);
  26488. if (index !== -1) {
  26489. // Remove from the scene if found
  26490. this.skeletons.splice(index, 1);
  26491. }
  26492. return index;
  26493. };
  26494. /**
  26495. * Remove a morph target for the list of scene's morph targets
  26496. * @param toRemove defines the morph target to remove
  26497. * @returns the index where the morph target was in the morph target list
  26498. */
  26499. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26500. var index = this.morphTargetManagers.indexOf(toRemove);
  26501. if (index !== -1) {
  26502. // Remove from the scene if found
  26503. this.morphTargetManagers.splice(index, 1);
  26504. }
  26505. return index;
  26506. };
  26507. /**
  26508. * Remove a light for the list of scene's lights
  26509. * @param toRemove defines the light to remove
  26510. * @returns the index where the light was in the light list
  26511. */
  26512. Scene.prototype.removeLight = function (toRemove) {
  26513. var index = this.lights.indexOf(toRemove);
  26514. if (index !== -1) {
  26515. // Remove from meshes
  26516. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26517. var mesh = _a[_i];
  26518. mesh._removeLightSource(toRemove);
  26519. }
  26520. // Remove from the scene if mesh found
  26521. this.lights.splice(index, 1);
  26522. this.sortLightsByPriority();
  26523. }
  26524. this.onLightRemovedObservable.notifyObservers(toRemove);
  26525. return index;
  26526. };
  26527. /**
  26528. * Remove a camera for the list of scene's cameras
  26529. * @param toRemove defines the camera to remove
  26530. * @returns the index where the camera was in the camera list
  26531. */
  26532. Scene.prototype.removeCamera = function (toRemove) {
  26533. var index = this.cameras.indexOf(toRemove);
  26534. if (index !== -1) {
  26535. // Remove from the scene if mesh found
  26536. this.cameras.splice(index, 1);
  26537. }
  26538. // Remove from activeCameras
  26539. var index2 = this.activeCameras.indexOf(toRemove);
  26540. if (index2 !== -1) {
  26541. // Remove from the scene if mesh found
  26542. this.activeCameras.splice(index2, 1);
  26543. }
  26544. // Reset the activeCamera
  26545. if (this.activeCamera === toRemove) {
  26546. if (this.cameras.length > 0) {
  26547. this.activeCamera = this.cameras[0];
  26548. }
  26549. else {
  26550. this.activeCamera = null;
  26551. }
  26552. }
  26553. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26554. return index;
  26555. };
  26556. /**
  26557. * Remove a particle system for the list of scene's particle systems
  26558. * @param toRemove defines the particle system to remove
  26559. * @returns the index where the particle system was in the particle system list
  26560. */
  26561. Scene.prototype.removeParticleSystem = function (toRemove) {
  26562. var index = this.particleSystems.indexOf(toRemove);
  26563. if (index !== -1) {
  26564. this.particleSystems.splice(index, 1);
  26565. }
  26566. return index;
  26567. };
  26568. /**
  26569. * Remove a animation for the list of scene's animations
  26570. * @param toRemove defines the animation to remove
  26571. * @returns the index where the animation was in the animation list
  26572. */
  26573. Scene.prototype.removeAnimation = function (toRemove) {
  26574. var index = this.animations.indexOf(toRemove);
  26575. if (index !== -1) {
  26576. this.animations.splice(index, 1);
  26577. }
  26578. return index;
  26579. };
  26580. /**
  26581. * Removes the given animation group from this scene.
  26582. * @param toRemove The animation group to remove
  26583. * @returns The index of the removed animation group
  26584. */
  26585. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26586. var index = this.animationGroups.indexOf(toRemove);
  26587. if (index !== -1) {
  26588. this.animationGroups.splice(index, 1);
  26589. }
  26590. return index;
  26591. };
  26592. /**
  26593. * Removes the given multi-material from this scene.
  26594. * @param toRemove The multi-material to remove
  26595. * @returns The index of the removed multi-material
  26596. */
  26597. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26598. var index = this.multiMaterials.indexOf(toRemove);
  26599. if (index !== -1) {
  26600. this.multiMaterials.splice(index, 1);
  26601. }
  26602. return index;
  26603. };
  26604. /**
  26605. * Removes the given material from this scene.
  26606. * @param toRemove The material to remove
  26607. * @returns The index of the removed material
  26608. */
  26609. Scene.prototype.removeMaterial = function (toRemove) {
  26610. var index = this.materials.indexOf(toRemove);
  26611. if (index !== -1) {
  26612. this.materials.splice(index, 1);
  26613. }
  26614. return index;
  26615. };
  26616. /**
  26617. * Removes the given lens flare system from this scene.
  26618. * @param toRemove The lens flare system to remove
  26619. * @returns The index of the removed lens flare system
  26620. */
  26621. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26622. var index = this.lensFlareSystems.indexOf(toRemove);
  26623. if (index !== -1) {
  26624. this.lensFlareSystems.splice(index, 1);
  26625. }
  26626. return index;
  26627. };
  26628. /**
  26629. * Removes the given action manager from this scene.
  26630. * @param toRemove The action manager to remove
  26631. * @returns The index of the removed action manager
  26632. */
  26633. Scene.prototype.removeActionManager = function (toRemove) {
  26634. var index = this._actionManagers.indexOf(toRemove);
  26635. if (index !== -1) {
  26636. this._actionManagers.splice(index, 1);
  26637. }
  26638. return index;
  26639. };
  26640. /**
  26641. * Removes the given effect layer from this scene.
  26642. * @param toRemove defines the effect layer to remove
  26643. * @returns the index of the removed effect layer
  26644. */
  26645. Scene.prototype.removeEffectLayer = function (toRemove) {
  26646. var index = this.effectLayers.indexOf(toRemove);
  26647. if (index !== -1) {
  26648. this.effectLayers.splice(index, 1);
  26649. }
  26650. return index;
  26651. };
  26652. /**
  26653. * Removes the given texture from this scene.
  26654. * @param toRemove The texture to remove
  26655. * @returns The index of the removed texture
  26656. */
  26657. Scene.prototype.removeTexture = function (toRemove) {
  26658. var index = this.textures.indexOf(toRemove);
  26659. if (index !== -1) {
  26660. this.textures.splice(index, 1);
  26661. }
  26662. return index;
  26663. };
  26664. /**
  26665. * Adds the given light to this scene
  26666. * @param newLight The light to add
  26667. */
  26668. Scene.prototype.addLight = function (newLight) {
  26669. this.lights.push(newLight);
  26670. this.sortLightsByPriority();
  26671. // Add light to all meshes (To support if the light is removed and then readded)
  26672. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26673. var mesh = _a[_i];
  26674. if (mesh._lightSources.indexOf(newLight) === -1) {
  26675. mesh._lightSources.push(newLight);
  26676. mesh._resyncLightSources();
  26677. }
  26678. }
  26679. this.onNewLightAddedObservable.notifyObservers(newLight);
  26680. };
  26681. /**
  26682. * Sorts the list list based on light priorities
  26683. */
  26684. Scene.prototype.sortLightsByPriority = function () {
  26685. if (this.requireLightSorting) {
  26686. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26687. }
  26688. };
  26689. /**
  26690. * Adds the given camera to this scene
  26691. * @param newCamera The camera to add
  26692. */
  26693. Scene.prototype.addCamera = function (newCamera) {
  26694. this.cameras.push(newCamera);
  26695. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26696. };
  26697. /**
  26698. * Adds the given skeleton to this scene
  26699. * @param newSkeleton The skeleton to add
  26700. */
  26701. Scene.prototype.addSkeleton = function (newSkeleton) {
  26702. this.skeletons.push(newSkeleton);
  26703. };
  26704. /**
  26705. * Adds the given particle system to this scene
  26706. * @param newParticleSystem The particle system to add
  26707. */
  26708. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26709. this.particleSystems.push(newParticleSystem);
  26710. };
  26711. /**
  26712. * Adds the given animation to this scene
  26713. * @param newAnimation The animation to add
  26714. */
  26715. Scene.prototype.addAnimation = function (newAnimation) {
  26716. this.animations.push(newAnimation);
  26717. };
  26718. /**
  26719. * Adds the given animation group to this scene.
  26720. * @param newAnimationGroup The animation group to add
  26721. */
  26722. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26723. this.animationGroups.push(newAnimationGroup);
  26724. };
  26725. /**
  26726. * Adds the given multi-material to this scene
  26727. * @param newMultiMaterial The multi-material to add
  26728. */
  26729. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26730. this.multiMaterials.push(newMultiMaterial);
  26731. };
  26732. /**
  26733. * Adds the given material to this scene
  26734. * @param newMaterial The material to add
  26735. */
  26736. Scene.prototype.addMaterial = function (newMaterial) {
  26737. this.materials.push(newMaterial);
  26738. };
  26739. /**
  26740. * Adds the given morph target to this scene
  26741. * @param newMorphTargetManager The morph target to add
  26742. */
  26743. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26744. this.morphTargetManagers.push(newMorphTargetManager);
  26745. };
  26746. /**
  26747. * Adds the given geometry to this scene
  26748. * @param newGeometry The geometry to add
  26749. */
  26750. Scene.prototype.addGeometry = function (newGeometry) {
  26751. this._geometries.push(newGeometry);
  26752. };
  26753. /**
  26754. * Adds the given lens flare system to this scene
  26755. * @param newLensFlareSystem The lens flare system to add
  26756. */
  26757. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26758. this.lensFlareSystems.push(newLensFlareSystem);
  26759. };
  26760. /**
  26761. * Adds the given effect layer to this scene
  26762. * @param newEffectLayer defines the effect layer to add
  26763. */
  26764. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26765. this.effectLayers.push(newEffectLayer);
  26766. };
  26767. /**
  26768. * Adds the given action manager to this scene
  26769. * @param newActionManager The action manager to add
  26770. */
  26771. Scene.prototype.addActionManager = function (newActionManager) {
  26772. this._actionManagers.push(newActionManager);
  26773. };
  26774. /**
  26775. * Adds the given texture to this scene.
  26776. * @param newTexture The texture to add
  26777. */
  26778. Scene.prototype.addTexture = function (newTexture) {
  26779. this.textures.push(newTexture);
  26780. };
  26781. /**
  26782. * Switch active camera
  26783. * @param newCamera defines the new active camera
  26784. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26785. */
  26786. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26787. if (attachControl === void 0) { attachControl = true; }
  26788. var canvas = this._engine.getRenderingCanvas();
  26789. if (!canvas) {
  26790. return;
  26791. }
  26792. if (this.activeCamera) {
  26793. this.activeCamera.detachControl(canvas);
  26794. }
  26795. this.activeCamera = newCamera;
  26796. if (attachControl) {
  26797. newCamera.attachControl(canvas);
  26798. }
  26799. };
  26800. /**
  26801. * sets the active camera of the scene using its ID
  26802. * @param id defines the camera's ID
  26803. * @return the new active camera or null if none found.
  26804. */
  26805. Scene.prototype.setActiveCameraByID = function (id) {
  26806. var camera = this.getCameraByID(id);
  26807. if (camera) {
  26808. this.activeCamera = camera;
  26809. return camera;
  26810. }
  26811. return null;
  26812. };
  26813. /**
  26814. * sets the active camera of the scene using its name
  26815. * @param name defines the camera's name
  26816. * @returns the new active camera or null if none found.
  26817. */
  26818. Scene.prototype.setActiveCameraByName = function (name) {
  26819. var camera = this.getCameraByName(name);
  26820. if (camera) {
  26821. this.activeCamera = camera;
  26822. return camera;
  26823. }
  26824. return null;
  26825. };
  26826. /**
  26827. * get an animation group using its name
  26828. * @param name defines the material's name
  26829. * @return the animation group or null if none found.
  26830. */
  26831. Scene.prototype.getAnimationGroupByName = function (name) {
  26832. for (var index = 0; index < this.animationGroups.length; index++) {
  26833. if (this.animationGroups[index].name === name) {
  26834. return this.animationGroups[index];
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * get a material using its id
  26841. * @param id defines the material's ID
  26842. * @return the material or null if none found.
  26843. */
  26844. Scene.prototype.getMaterialByID = function (id) {
  26845. for (var index = 0; index < this.materials.length; index++) {
  26846. if (this.materials[index].id === id) {
  26847. return this.materials[index];
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Gets a material using its name
  26854. * @param name defines the material's name
  26855. * @return the material or null if none found.
  26856. */
  26857. Scene.prototype.getMaterialByName = function (name) {
  26858. for (var index = 0; index < this.materials.length; index++) {
  26859. if (this.materials[index].name === name) {
  26860. return this.materials[index];
  26861. }
  26862. }
  26863. return null;
  26864. };
  26865. /**
  26866. * Gets a lens flare system using its name
  26867. * @param name defines the name to look for
  26868. * @returns the lens flare system or null if not found
  26869. */
  26870. Scene.prototype.getLensFlareSystemByName = function (name) {
  26871. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26872. if (this.lensFlareSystems[index].name === name) {
  26873. return this.lensFlareSystems[index];
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. /**
  26879. * Gets a lens flare system using its id
  26880. * @param id defines the id to look for
  26881. * @returns the lens flare system or null if not found
  26882. */
  26883. Scene.prototype.getLensFlareSystemByID = function (id) {
  26884. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26885. if (this.lensFlareSystems[index].id === id) {
  26886. return this.lensFlareSystems[index];
  26887. }
  26888. }
  26889. return null;
  26890. };
  26891. /**
  26892. * Gets a camera using its id
  26893. * @param id defines the id to look for
  26894. * @returns the camera or null if not found
  26895. */
  26896. Scene.prototype.getCameraByID = function (id) {
  26897. for (var index = 0; index < this.cameras.length; index++) {
  26898. if (this.cameras[index].id === id) {
  26899. return this.cameras[index];
  26900. }
  26901. }
  26902. return null;
  26903. };
  26904. /**
  26905. * Gets a camera using its unique id
  26906. * @param uniqueId defines the unique id to look for
  26907. * @returns the camera or null if not found
  26908. */
  26909. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26910. for (var index = 0; index < this.cameras.length; index++) {
  26911. if (this.cameras[index].uniqueId === uniqueId) {
  26912. return this.cameras[index];
  26913. }
  26914. }
  26915. return null;
  26916. };
  26917. /**
  26918. * Gets a camera using its name
  26919. * @param name defines the camera's name
  26920. * @return the camera or null if none found.
  26921. */
  26922. Scene.prototype.getCameraByName = function (name) {
  26923. for (var index = 0; index < this.cameras.length; index++) {
  26924. if (this.cameras[index].name === name) {
  26925. return this.cameras[index];
  26926. }
  26927. }
  26928. return null;
  26929. };
  26930. /**
  26931. * Gets a bone using its id
  26932. * @param id defines the bone's id
  26933. * @return the bone or null if not found
  26934. */
  26935. Scene.prototype.getBoneByID = function (id) {
  26936. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26937. var skeleton = this.skeletons[skeletonIndex];
  26938. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26939. if (skeleton.bones[boneIndex].id === id) {
  26940. return skeleton.bones[boneIndex];
  26941. }
  26942. }
  26943. }
  26944. return null;
  26945. };
  26946. /**
  26947. * Gets a bone using its id
  26948. * @param name defines the bone's name
  26949. * @return the bone or null if not found
  26950. */
  26951. Scene.prototype.getBoneByName = function (name) {
  26952. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26953. var skeleton = this.skeletons[skeletonIndex];
  26954. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26955. if (skeleton.bones[boneIndex].name === name) {
  26956. return skeleton.bones[boneIndex];
  26957. }
  26958. }
  26959. }
  26960. return null;
  26961. };
  26962. /**
  26963. * Gets a light node using its name
  26964. * @param name defines the the light's name
  26965. * @return the light or null if none found.
  26966. */
  26967. Scene.prototype.getLightByName = function (name) {
  26968. for (var index = 0; index < this.lights.length; index++) {
  26969. if (this.lights[index].name === name) {
  26970. return this.lights[index];
  26971. }
  26972. }
  26973. return null;
  26974. };
  26975. /**
  26976. * Gets a light node using its id
  26977. * @param id defines the light's id
  26978. * @return the light or null if none found.
  26979. */
  26980. Scene.prototype.getLightByID = function (id) {
  26981. for (var index = 0; index < this.lights.length; index++) {
  26982. if (this.lights[index].id === id) {
  26983. return this.lights[index];
  26984. }
  26985. }
  26986. return null;
  26987. };
  26988. /**
  26989. * Gets a light node using its scene-generated unique ID
  26990. * @param uniqueId defines the light's unique id
  26991. * @return the light or null if none found.
  26992. */
  26993. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26994. for (var index = 0; index < this.lights.length; index++) {
  26995. if (this.lights[index].uniqueId === uniqueId) {
  26996. return this.lights[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets a particle system by id
  27003. * @param id defines the particle system id
  27004. * @return the corresponding system or null if none found
  27005. */
  27006. Scene.prototype.getParticleSystemByID = function (id) {
  27007. for (var index = 0; index < this.particleSystems.length; index++) {
  27008. if (this.particleSystems[index].id === id) {
  27009. return this.particleSystems[index];
  27010. }
  27011. }
  27012. return null;
  27013. };
  27014. /**
  27015. * Gets a geometry using its ID
  27016. * @param id defines the geometry's id
  27017. * @return the geometry or null if none found.
  27018. */
  27019. Scene.prototype.getGeometryByID = function (id) {
  27020. for (var index = 0; index < this._geometries.length; index++) {
  27021. if (this._geometries[index].id === id) {
  27022. return this._geometries[index];
  27023. }
  27024. }
  27025. return null;
  27026. };
  27027. /**
  27028. * Add a new geometry to this scene
  27029. * @param geometry defines the geometry to be added to the scene.
  27030. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27031. * @return a boolean defining if the geometry was added or not
  27032. */
  27033. Scene.prototype.pushGeometry = function (geometry, force) {
  27034. if (!force && this.getGeometryByID(geometry.id)) {
  27035. return false;
  27036. }
  27037. this._geometries.push(geometry);
  27038. //notify the collision coordinator
  27039. if (this.collisionCoordinator) {
  27040. this.collisionCoordinator.onGeometryAdded(geometry);
  27041. }
  27042. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27043. return true;
  27044. };
  27045. /**
  27046. * Removes an existing geometry
  27047. * @param geometry defines the geometry to be removed from the scene
  27048. * @return a boolean defining if the geometry was removed or not
  27049. */
  27050. Scene.prototype.removeGeometry = function (geometry) {
  27051. var index = this._geometries.indexOf(geometry);
  27052. if (index > -1) {
  27053. this._geometries.splice(index, 1);
  27054. //notify the collision coordinator
  27055. if (this.collisionCoordinator) {
  27056. this.collisionCoordinator.onGeometryDeleted(geometry);
  27057. }
  27058. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27059. return true;
  27060. }
  27061. return false;
  27062. };
  27063. /**
  27064. * Gets the list of geometries attached to the scene
  27065. * @returns an array of Geometry
  27066. */
  27067. Scene.prototype.getGeometries = function () {
  27068. return this._geometries;
  27069. };
  27070. /**
  27071. * Gets the first added mesh found of a given ID
  27072. * @param id defines the id to search for
  27073. * @return the mesh found or null if not found at all
  27074. */
  27075. Scene.prototype.getMeshByID = function (id) {
  27076. for (var index = 0; index < this.meshes.length; index++) {
  27077. if (this.meshes[index].id === id) {
  27078. return this.meshes[index];
  27079. }
  27080. }
  27081. return null;
  27082. };
  27083. /**
  27084. * Gets a list of meshes using their id
  27085. * @param id defines the id to search for
  27086. * @returns a list of meshes
  27087. */
  27088. Scene.prototype.getMeshesByID = function (id) {
  27089. return this.meshes.filter(function (m) {
  27090. return m.id === id;
  27091. });
  27092. };
  27093. /**
  27094. * Gets the first added transform node found of a given ID
  27095. * @param id defines the id to search for
  27096. * @return the found transform node or null if not found at all.
  27097. */
  27098. Scene.prototype.getTransformNodeByID = function (id) {
  27099. for (var index = 0; index < this.transformNodes.length; index++) {
  27100. if (this.transformNodes[index].id === id) {
  27101. return this.transformNodes[index];
  27102. }
  27103. }
  27104. return null;
  27105. };
  27106. /**
  27107. * Gets a list of transform nodes using their id
  27108. * @param id defines the id to search for
  27109. * @returns a list of transform nodes
  27110. */
  27111. Scene.prototype.getTransformNodesByID = function (id) {
  27112. return this.transformNodes.filter(function (m) {
  27113. return m.id === id;
  27114. });
  27115. };
  27116. /**
  27117. * Gets a mesh with its auto-generated unique id
  27118. * @param uniqueId defines the unique id to search for
  27119. * @return the found mesh or null if not found at all.
  27120. */
  27121. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27122. for (var index = 0; index < this.meshes.length; index++) {
  27123. if (this.meshes[index].uniqueId === uniqueId) {
  27124. return this.meshes[index];
  27125. }
  27126. }
  27127. return null;
  27128. };
  27129. /**
  27130. * Gets a the last added mesh using a given id
  27131. * @param id defines the id to search for
  27132. * @return the found mesh or null if not found at all.
  27133. */
  27134. Scene.prototype.getLastMeshByID = function (id) {
  27135. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27136. if (this.meshes[index].id === id) {
  27137. return this.meshes[index];
  27138. }
  27139. }
  27140. return null;
  27141. };
  27142. /**
  27143. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27144. * @param id defines the id to search for
  27145. * @return the found node or null if not found at all
  27146. */
  27147. Scene.prototype.getLastEntryByID = function (id) {
  27148. var index;
  27149. for (index = this.meshes.length - 1; index >= 0; index--) {
  27150. if (this.meshes[index].id === id) {
  27151. return this.meshes[index];
  27152. }
  27153. }
  27154. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27155. if (this.transformNodes[index].id === id) {
  27156. return this.transformNodes[index];
  27157. }
  27158. }
  27159. for (index = this.cameras.length - 1; index >= 0; index--) {
  27160. if (this.cameras[index].id === id) {
  27161. return this.cameras[index];
  27162. }
  27163. }
  27164. for (index = this.lights.length - 1; index >= 0; index--) {
  27165. if (this.lights[index].id === id) {
  27166. return this.lights[index];
  27167. }
  27168. }
  27169. return null;
  27170. };
  27171. /**
  27172. * Gets a node (Mesh, Camera, Light) using a given id
  27173. * @param id defines the id to search for
  27174. * @return the found node or null if not found at all
  27175. */
  27176. Scene.prototype.getNodeByID = function (id) {
  27177. var mesh = this.getMeshByID(id);
  27178. if (mesh) {
  27179. return mesh;
  27180. }
  27181. var light = this.getLightByID(id);
  27182. if (light) {
  27183. return light;
  27184. }
  27185. var camera = this.getCameraByID(id);
  27186. if (camera) {
  27187. return camera;
  27188. }
  27189. var bone = this.getBoneByID(id);
  27190. return bone;
  27191. };
  27192. /**
  27193. * Gets a node (Mesh, Camera, Light) using a given name
  27194. * @param name defines the name to search for
  27195. * @return the found node or null if not found at all.
  27196. */
  27197. Scene.prototype.getNodeByName = function (name) {
  27198. var mesh = this.getMeshByName(name);
  27199. if (mesh) {
  27200. return mesh;
  27201. }
  27202. var light = this.getLightByName(name);
  27203. if (light) {
  27204. return light;
  27205. }
  27206. var camera = this.getCameraByName(name);
  27207. if (camera) {
  27208. return camera;
  27209. }
  27210. var bone = this.getBoneByName(name);
  27211. return bone;
  27212. };
  27213. /**
  27214. * Gets a mesh using a given name
  27215. * @param name defines the name to search for
  27216. * @return the found mesh or null if not found at all.
  27217. */
  27218. Scene.prototype.getMeshByName = function (name) {
  27219. for (var index = 0; index < this.meshes.length; index++) {
  27220. if (this.meshes[index].name === name) {
  27221. return this.meshes[index];
  27222. }
  27223. }
  27224. return null;
  27225. };
  27226. /**
  27227. * Gets a transform node using a given name
  27228. * @param name defines the name to search for
  27229. * @return the found transform node or null if not found at all.
  27230. */
  27231. Scene.prototype.getTransformNodeByName = function (name) {
  27232. for (var index = 0; index < this.transformNodes.length; index++) {
  27233. if (this.transformNodes[index].name === name) {
  27234. return this.transformNodes[index];
  27235. }
  27236. }
  27237. return null;
  27238. };
  27239. /**
  27240. * Gets a sound using a given name
  27241. * @param name defines the name to search for
  27242. * @return the found sound or null if not found at all.
  27243. */
  27244. Scene.prototype.getSoundByName = function (name) {
  27245. var index;
  27246. if (BABYLON.AudioEngine) {
  27247. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27248. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27249. return this.mainSoundTrack.soundCollection[index];
  27250. }
  27251. }
  27252. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27253. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27254. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27255. return this.soundTracks[sdIndex].soundCollection[index];
  27256. }
  27257. }
  27258. }
  27259. }
  27260. return null;
  27261. };
  27262. /**
  27263. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27264. * @param id defines the id to search for
  27265. * @return the found skeleton or null if not found at all.
  27266. */
  27267. Scene.prototype.getLastSkeletonByID = function (id) {
  27268. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27269. if (this.skeletons[index].id === id) {
  27270. return this.skeletons[index];
  27271. }
  27272. }
  27273. return null;
  27274. };
  27275. /**
  27276. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27277. * @param id defines the id to search for
  27278. * @return the found skeleton or null if not found at all.
  27279. */
  27280. Scene.prototype.getSkeletonById = function (id) {
  27281. for (var index = 0; index < this.skeletons.length; index++) {
  27282. if (this.skeletons[index].id === id) {
  27283. return this.skeletons[index];
  27284. }
  27285. }
  27286. return null;
  27287. };
  27288. /**
  27289. * Gets a skeleton using a given name
  27290. * @param name defines the name to search for
  27291. * @return the found skeleton or null if not found at all.
  27292. */
  27293. Scene.prototype.getSkeletonByName = function (name) {
  27294. for (var index = 0; index < this.skeletons.length; index++) {
  27295. if (this.skeletons[index].name === name) {
  27296. return this.skeletons[index];
  27297. }
  27298. }
  27299. return null;
  27300. };
  27301. /**
  27302. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27303. * @param id defines the id to search for
  27304. * @return the found morph target manager or null if not found at all.
  27305. */
  27306. Scene.prototype.getMorphTargetManagerById = function (id) {
  27307. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27308. if (this.morphTargetManagers[index].uniqueId === id) {
  27309. return this.morphTargetManagers[index];
  27310. }
  27311. }
  27312. return null;
  27313. };
  27314. /**
  27315. * Gets a boolean indicating if the given mesh is active
  27316. * @param mesh defines the mesh to look for
  27317. * @returns true if the mesh is in the active list
  27318. */
  27319. Scene.prototype.isActiveMesh = function (mesh) {
  27320. return (this._activeMeshes.indexOf(mesh) !== -1);
  27321. };
  27322. /**
  27323. * Return a the first highlight layer of the scene with a given name.
  27324. * @param name The name of the highlight layer to look for.
  27325. * @return The highlight layer if found otherwise null.
  27326. */
  27327. Scene.prototype.getHighlightLayerByName = function (name) {
  27328. for (var index = 0; index < this.effectLayers.length; index++) {
  27329. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27330. return this.effectLayers[index];
  27331. }
  27332. }
  27333. return null;
  27334. };
  27335. /**
  27336. * Return a the first highlight layer of the scene with a given name.
  27337. * @param name The name of the highlight layer to look for.
  27338. * @return The highlight layer if found otherwise null.
  27339. */
  27340. Scene.prototype.getGlowLayerByName = function (name) {
  27341. for (var index = 0; index < this.effectLayers.length; index++) {
  27342. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27343. return this.effectLayers[index];
  27344. }
  27345. }
  27346. return null;
  27347. };
  27348. Object.defineProperty(Scene.prototype, "uid", {
  27349. /**
  27350. * Return a unique id as a string which can serve as an identifier for the scene
  27351. */
  27352. get: function () {
  27353. if (!this._uid) {
  27354. this._uid = BABYLON.Tools.RandomId();
  27355. }
  27356. return this._uid;
  27357. },
  27358. enumerable: true,
  27359. configurable: true
  27360. });
  27361. /**
  27362. * Add an externaly attached data from its key.
  27363. * This method call will fail and return false, if such key already exists.
  27364. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27365. * @param key the unique key that identifies the data
  27366. * @param data the data object to associate to the key for this Engine instance
  27367. * @return true if no such key were already present and the data was added successfully, false otherwise
  27368. */
  27369. Scene.prototype.addExternalData = function (key, data) {
  27370. if (!this._externalData) {
  27371. this._externalData = new BABYLON.StringDictionary();
  27372. }
  27373. return this._externalData.add(key, data);
  27374. };
  27375. /**
  27376. * Get an externaly attached data from its key
  27377. * @param key the unique key that identifies the data
  27378. * @return the associated data, if present (can be null), or undefined if not present
  27379. */
  27380. Scene.prototype.getExternalData = function (key) {
  27381. if (!this._externalData) {
  27382. return null;
  27383. }
  27384. return this._externalData.get(key);
  27385. };
  27386. /**
  27387. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27388. * @param key the unique key that identifies the data
  27389. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27390. * @return the associated data, can be null if the factory returned null.
  27391. */
  27392. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27393. if (!this._externalData) {
  27394. this._externalData = new BABYLON.StringDictionary();
  27395. }
  27396. return this._externalData.getOrAddWithFactory(key, factory);
  27397. };
  27398. /**
  27399. * Remove an externaly attached data from the Engine instance
  27400. * @param key the unique key that identifies the data
  27401. * @return true if the data was successfully removed, false if it doesn't exist
  27402. */
  27403. Scene.prototype.removeExternalData = function (key) {
  27404. return this._externalData.remove(key);
  27405. };
  27406. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27407. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27408. if (mesh.showSubMeshesBoundingBox) {
  27409. var boundingInfo = subMesh.getBoundingInfo();
  27410. if (boundingInfo !== null && boundingInfo !== undefined) {
  27411. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27412. }
  27413. }
  27414. var material = subMesh.getMaterial();
  27415. if (material !== null && material !== undefined) {
  27416. // Render targets
  27417. if (material.getRenderTargetTextures !== undefined) {
  27418. if (this._processedMaterials.indexOf(material) === -1) {
  27419. this._processedMaterials.push(material);
  27420. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27421. }
  27422. }
  27423. // Dispatch
  27424. this._activeIndices.addCount(subMesh.indexCount, false);
  27425. this._renderingManager.dispatch(subMesh, mesh, material);
  27426. }
  27427. }
  27428. };
  27429. /**
  27430. * Clear the processed materials smart array preventing retention point in material dispose.
  27431. */
  27432. Scene.prototype.freeProcessedMaterials = function () {
  27433. this._processedMaterials.dispose();
  27434. };
  27435. /**
  27436. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27437. */
  27438. Scene.prototype.freeActiveMeshes = function () {
  27439. this._activeMeshes.dispose();
  27440. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27441. this.activeCamera._activeMeshes.dispose();
  27442. }
  27443. if (this.activeCameras) {
  27444. for (var i = 0; i < this.activeCameras.length; i++) {
  27445. var activeCamera = this.activeCameras[i];
  27446. if (activeCamera && activeCamera._activeMeshes) {
  27447. activeCamera._activeMeshes.dispose();
  27448. }
  27449. }
  27450. }
  27451. };
  27452. /**
  27453. * Clear the info related to rendering groups preventing retention points during dispose.
  27454. */
  27455. Scene.prototype.freeRenderingGroups = function () {
  27456. if (this._renderingManager) {
  27457. this._renderingManager.freeRenderingGroups();
  27458. }
  27459. if (this.textures) {
  27460. for (var i = 0; i < this.textures.length; i++) {
  27461. var texture = this.textures[i];
  27462. if (texture && texture.renderList) {
  27463. texture.freeRenderingGroups();
  27464. }
  27465. }
  27466. }
  27467. };
  27468. /** @hidden */
  27469. Scene.prototype._isInIntermediateRendering = function () {
  27470. return this._intermediateRendering;
  27471. };
  27472. /**
  27473. * Defines the current active mesh candidate provider
  27474. * @param provider defines the provider to use
  27475. */
  27476. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27477. this._activeMeshCandidateProvider = provider;
  27478. };
  27479. /**
  27480. * Gets the current active mesh candidate provider
  27481. * @returns the current active mesh candidate provider
  27482. */
  27483. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27484. return this._activeMeshCandidateProvider;
  27485. };
  27486. /**
  27487. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27488. * @returns the current scene
  27489. */
  27490. Scene.prototype.freezeActiveMeshes = function () {
  27491. if (!this.activeCamera) {
  27492. return this;
  27493. }
  27494. if (!this._frustumPlanes) {
  27495. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27496. }
  27497. this._evaluateActiveMeshes();
  27498. this._activeMeshesFrozen = true;
  27499. return this;
  27500. };
  27501. /**
  27502. * Use this function to restart evaluating active meshes on every frame
  27503. * @returns the current scene
  27504. */
  27505. Scene.prototype.unfreezeActiveMeshes = function () {
  27506. this._activeMeshesFrozen = false;
  27507. return this;
  27508. };
  27509. Scene.prototype._evaluateActiveMeshes = function () {
  27510. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27511. return;
  27512. }
  27513. if (!this.activeCamera) {
  27514. return;
  27515. }
  27516. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27517. this.activeCamera._activeMeshes.reset();
  27518. this._activeMeshes.reset();
  27519. this._renderingManager.reset();
  27520. this._processedMaterials.reset();
  27521. this._activeParticleSystems.reset();
  27522. this._activeSkeletons.reset();
  27523. this._softwareSkinnedMeshes.reset();
  27524. if (this._boundingBoxRenderer) {
  27525. this._boundingBoxRenderer.reset();
  27526. }
  27527. // Meshes
  27528. var meshes;
  27529. var len;
  27530. var checkIsEnabled = true;
  27531. // Determine mesh candidates
  27532. if (this._activeMeshCandidateProvider !== undefined) {
  27533. // Use _activeMeshCandidateProvider
  27534. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27535. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27536. if (meshes !== undefined) {
  27537. len = meshes.length;
  27538. }
  27539. else {
  27540. len = 0;
  27541. }
  27542. }
  27543. else if (this._selectionOctree !== undefined) {
  27544. // Octree
  27545. var selection = this._selectionOctree.select(this._frustumPlanes);
  27546. meshes = selection.data;
  27547. len = selection.length;
  27548. }
  27549. else {
  27550. // Full scene traversal
  27551. len = this.meshes.length;
  27552. meshes = this.meshes;
  27553. }
  27554. // Check each mesh
  27555. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27556. mesh = meshes[meshIndex];
  27557. if (mesh.isBlocked) {
  27558. continue;
  27559. }
  27560. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27561. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27562. continue;
  27563. }
  27564. mesh.computeWorldMatrix();
  27565. // Intersections
  27566. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27567. this._meshesForIntersections.pushNoDuplicate(mesh);
  27568. }
  27569. // Switch to current LOD
  27570. meshLOD = mesh.getLOD(this.activeCamera);
  27571. if (meshLOD === undefined || meshLOD === null) {
  27572. continue;
  27573. }
  27574. mesh._preActivate();
  27575. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27576. this._activeMeshes.push(mesh);
  27577. this.activeCamera._activeMeshes.push(mesh);
  27578. mesh._activate(this._renderId);
  27579. if (meshLOD !== mesh) {
  27580. meshLOD._activate(this._renderId);
  27581. }
  27582. this._activeMesh(mesh, meshLOD);
  27583. }
  27584. }
  27585. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27586. // Particle systems
  27587. if (this.particlesEnabled) {
  27588. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27589. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27590. var particleSystem = this.particleSystems[particleIndex];
  27591. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27592. continue;
  27593. }
  27594. var emitter = particleSystem.emitter;
  27595. if (!emitter.position || emitter.isEnabled()) {
  27596. this._activeParticleSystems.push(particleSystem);
  27597. particleSystem.animate();
  27598. this._renderingManager.dispatchParticles(particleSystem);
  27599. }
  27600. }
  27601. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27602. }
  27603. };
  27604. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27605. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27606. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27607. mesh.skeleton.prepare();
  27608. }
  27609. if (!mesh.computeBonesUsingShaders) {
  27610. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27611. }
  27612. }
  27613. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27614. var boundingInfo = sourceMesh.getBoundingInfo();
  27615. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27616. }
  27617. if (mesh !== undefined && mesh !== null
  27618. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27619. // Submeshes Octrees
  27620. var len;
  27621. var subMeshes;
  27622. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27623. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27624. len = intersections.length;
  27625. subMeshes = intersections.data;
  27626. }
  27627. else {
  27628. subMeshes = mesh.subMeshes;
  27629. len = subMeshes.length;
  27630. }
  27631. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27632. subMesh = subMeshes[subIndex];
  27633. this._evaluateSubMesh(subMesh, mesh);
  27634. }
  27635. }
  27636. };
  27637. /**
  27638. * Update the transform matrix to update from the current active camera
  27639. * @param force defines a boolean used to force the update even if cache is up to date
  27640. */
  27641. Scene.prototype.updateTransformMatrix = function (force) {
  27642. if (!this.activeCamera) {
  27643. return;
  27644. }
  27645. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27646. };
  27647. /**
  27648. * 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)
  27649. * @param alternateCamera defines the camera to use
  27650. */
  27651. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27652. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27653. };
  27654. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27655. if (camera && camera._skipRendering) {
  27656. return;
  27657. }
  27658. var engine = this._engine;
  27659. this.activeCamera = camera;
  27660. if (!this.activeCamera)
  27661. throw new Error("Active camera not set");
  27662. // Viewport
  27663. engine.setViewport(this.activeCamera.viewport);
  27664. // Camera
  27665. this.resetCachedMaterial();
  27666. this._renderId++;
  27667. this.updateTransformMatrix();
  27668. if (camera._alternateCamera) {
  27669. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27670. this._alternateRendering = true;
  27671. }
  27672. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27673. // Meshes
  27674. this._evaluateActiveMeshes();
  27675. // Software skinning
  27676. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27677. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27678. mesh.applySkeleton(mesh.skeleton);
  27679. }
  27680. // Render targets
  27681. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27682. var needsRestoreFrameBuffer = false;
  27683. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27684. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27685. }
  27686. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27687. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27688. }
  27689. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27690. this._intermediateRendering = true;
  27691. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27692. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27693. var renderTarget = this._renderTargets.data[renderIndex];
  27694. if (renderTarget._shouldRender()) {
  27695. this._renderId++;
  27696. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27697. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27698. }
  27699. }
  27700. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27701. this._intermediateRendering = false;
  27702. this._renderId++;
  27703. needsRestoreFrameBuffer = true; // Restore back buffer
  27704. }
  27705. // Render EffectLayer Texture
  27706. var stencilState = this._engine.getStencilBuffer();
  27707. var renderEffects = false;
  27708. var needStencil = false;
  27709. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27710. this._intermediateRendering = true;
  27711. for (var i = 0; i < this.effectLayers.length; i++) {
  27712. var effectLayer = this.effectLayers[i];
  27713. if (effectLayer.shouldRender() &&
  27714. (!effectLayer.camera ||
  27715. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27716. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27717. renderEffects = true;
  27718. needStencil = needStencil || effectLayer.needStencil();
  27719. var renderTarget = effectLayer._mainTexture;
  27720. if (renderTarget._shouldRender()) {
  27721. this._renderId++;
  27722. renderTarget.render(false, false);
  27723. needsRestoreFrameBuffer = true;
  27724. }
  27725. }
  27726. }
  27727. this._intermediateRendering = false;
  27728. this._renderId++;
  27729. }
  27730. if (needsRestoreFrameBuffer) {
  27731. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27732. }
  27733. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27734. // Prepare Frame
  27735. if (this.postProcessManager) {
  27736. this.postProcessManager._prepareFrame();
  27737. }
  27738. // Backgrounds
  27739. var layerIndex;
  27740. var layer;
  27741. if (this.layers.length) {
  27742. engine.setDepthBuffer(false);
  27743. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27744. layer = this.layers[layerIndex];
  27745. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27746. layer.render();
  27747. }
  27748. }
  27749. engine.setDepthBuffer(true);
  27750. }
  27751. // Activate effect Layer stencil
  27752. if (needStencil) {
  27753. this._engine.setStencilBuffer(true);
  27754. }
  27755. // Render
  27756. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27757. this._renderingManager.render(null, null, true, true);
  27758. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27759. // Restore effect Layer stencil
  27760. if (needStencil) {
  27761. this._engine.setStencilBuffer(stencilState);
  27762. }
  27763. // Bounding boxes
  27764. if (this._boundingBoxRenderer) {
  27765. this._boundingBoxRenderer.render();
  27766. }
  27767. // Lens flares
  27768. if (this.lensFlaresEnabled) {
  27769. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27770. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27771. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27772. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27773. lensFlareSystem.render();
  27774. }
  27775. }
  27776. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27777. }
  27778. // Effect Layer
  27779. if (renderEffects) {
  27780. engine.setDepthBuffer(false);
  27781. for (var i = 0; i < this.effectLayers.length; i++) {
  27782. if (this.effectLayers[i].shouldRender()) {
  27783. this.effectLayers[i].render();
  27784. }
  27785. }
  27786. engine.setDepthBuffer(true);
  27787. }
  27788. // Foregrounds
  27789. if (this.layers.length) {
  27790. engine.setDepthBuffer(false);
  27791. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27792. layer = this.layers[layerIndex];
  27793. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27794. layer.render();
  27795. }
  27796. }
  27797. engine.setDepthBuffer(true);
  27798. }
  27799. // Finalize frame
  27800. if (this.postProcessManager) {
  27801. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27802. }
  27803. // Reset some special arrays
  27804. this._renderTargets.reset();
  27805. this._alternateRendering = false;
  27806. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27807. };
  27808. Scene.prototype._processSubCameras = function (camera) {
  27809. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27810. this._renderForCamera(camera);
  27811. return;
  27812. }
  27813. // rig cameras
  27814. for (var index = 0; index < camera._rigCameras.length; index++) {
  27815. this._renderForCamera(camera._rigCameras[index], camera);
  27816. }
  27817. this.activeCamera = camera;
  27818. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27819. };
  27820. Scene.prototype._checkIntersections = function () {
  27821. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27822. var sourceMesh = this._meshesForIntersections.data[index];
  27823. if (!sourceMesh.actionManager) {
  27824. continue;
  27825. }
  27826. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27827. var action = sourceMesh.actionManager.actions[actionIndex];
  27828. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27829. var parameters = action.getTriggerParameter();
  27830. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27831. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27832. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27833. if (areIntersecting && currentIntersectionInProgress === -1) {
  27834. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27835. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27836. sourceMesh._intersectionsInProgress.push(otherMesh);
  27837. }
  27838. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27839. sourceMesh._intersectionsInProgress.push(otherMesh);
  27840. }
  27841. }
  27842. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27843. //They intersected, and now they don't.
  27844. //is this trigger an exit trigger? execute an event.
  27845. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27846. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27847. }
  27848. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27849. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27850. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27851. return otherMesh === parameterMesh;
  27852. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27853. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27854. }
  27855. }
  27856. }
  27857. }
  27858. }
  27859. };
  27860. /**
  27861. * Render the scene
  27862. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27863. */
  27864. Scene.prototype.render = function (updateCameras) {
  27865. if (updateCameras === void 0) { updateCameras = true; }
  27866. if (this.isDisposed) {
  27867. return;
  27868. }
  27869. this._activeParticles.fetchNewFrame();
  27870. this._totalVertices.fetchNewFrame();
  27871. this._activeIndices.fetchNewFrame();
  27872. this._activeBones.fetchNewFrame();
  27873. this._meshesForIntersections.reset();
  27874. this.resetCachedMaterial();
  27875. this.onBeforeAnimationsObservable.notifyObservers(this);
  27876. // Actions
  27877. if (this.actionManager) {
  27878. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27879. }
  27880. //Simplification Queue
  27881. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27882. this.simplificationQueue.executeNext();
  27883. }
  27884. if (this._engine.isDeterministicLockStep()) {
  27885. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27886. var defaultFPS = (60.0 / 1000.0);
  27887. var defaultFrameTime = 1000 / 60; // frame time in MS
  27888. if (this._physicsEngine) {
  27889. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27890. }
  27891. var stepsTaken = 0;
  27892. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27893. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27894. internalSteps = Math.min(internalSteps, maxSubSteps);
  27895. do {
  27896. this.onBeforeStepObservable.notifyObservers(this);
  27897. // Animations
  27898. this._animationRatio = defaultFrameTime * defaultFPS;
  27899. this._animate();
  27900. this.onAfterAnimationsObservable.notifyObservers(this);
  27901. // Physics
  27902. if (this._physicsEngine) {
  27903. this.onBeforePhysicsObservable.notifyObservers(this);
  27904. this._physicsEngine._step(defaultFrameTime / 1000);
  27905. this.onAfterPhysicsObservable.notifyObservers(this);
  27906. }
  27907. this.onAfterStepObservable.notifyObservers(this);
  27908. this._currentStepId++;
  27909. stepsTaken++;
  27910. deltaTime -= defaultFrameTime;
  27911. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27912. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27913. }
  27914. else {
  27915. // Animations
  27916. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27917. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27918. this._animate();
  27919. this.onAfterAnimationsObservable.notifyObservers(this);
  27920. // Physics
  27921. if (this._physicsEngine) {
  27922. this.onBeforePhysicsObservable.notifyObservers(this);
  27923. this._physicsEngine._step(deltaTime / 1000.0);
  27924. this.onAfterPhysicsObservable.notifyObservers(this);
  27925. }
  27926. }
  27927. // update gamepad manager
  27928. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27929. this._gamepadManager._checkGamepadsStatus();
  27930. }
  27931. // Update Cameras
  27932. if (updateCameras) {
  27933. if (this.activeCameras.length > 0) {
  27934. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27935. var camera = this.activeCameras[cameraIndex];
  27936. camera.update();
  27937. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27938. // rig cameras
  27939. for (var index = 0; index < camera._rigCameras.length; index++) {
  27940. camera._rigCameras[index].update();
  27941. }
  27942. }
  27943. }
  27944. }
  27945. else if (this.activeCamera) {
  27946. this.activeCamera.update();
  27947. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27948. // rig cameras
  27949. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27950. this.activeCamera._rigCameras[index].update();
  27951. }
  27952. }
  27953. }
  27954. }
  27955. // Before render
  27956. this.onBeforeRenderObservable.notifyObservers(this);
  27957. // Customs render targets
  27958. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27959. var engine = this.getEngine();
  27960. var currentActiveCamera = this.activeCamera;
  27961. if (this.renderTargetsEnabled) {
  27962. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27963. this._intermediateRendering = true;
  27964. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27965. var renderTarget = this.customRenderTargets[customIndex];
  27966. if (renderTarget._shouldRender()) {
  27967. this._renderId++;
  27968. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27969. if (!this.activeCamera)
  27970. throw new Error("Active camera not set");
  27971. // Viewport
  27972. engine.setViewport(this.activeCamera.viewport);
  27973. // Camera
  27974. this.updateTransformMatrix();
  27975. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27976. }
  27977. }
  27978. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27979. this._intermediateRendering = false;
  27980. this._renderId++;
  27981. }
  27982. // Restore back buffer
  27983. if (this.customRenderTargets.length > 0) {
  27984. engine.restoreDefaultFramebuffer();
  27985. }
  27986. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27987. this.activeCamera = currentActiveCamera;
  27988. // Procedural textures
  27989. if (this.proceduralTexturesEnabled) {
  27990. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27991. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27992. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27993. if (proceduralTexture._shouldRender()) {
  27994. proceduralTexture.render();
  27995. }
  27996. }
  27997. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27998. }
  27999. // Clear
  28000. if (this.autoClearDepthAndStencil || this.autoClear) {
  28001. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28002. }
  28003. // Shadows
  28004. if (this.shadowsEnabled) {
  28005. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28006. var light = this.lights[lightIndex];
  28007. var shadowGenerator = light.getShadowGenerator();
  28008. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28009. var shadowMap = (shadowGenerator.getShadowMap());
  28010. if (this.textures.indexOf(shadowMap) !== -1) {
  28011. this._renderTargets.push(shadowMap);
  28012. }
  28013. }
  28014. }
  28015. }
  28016. // Depth renderer
  28017. for (var key in this._depthRenderer) {
  28018. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28019. }
  28020. // Geometry renderer
  28021. if (this._geometryBufferRenderer) {
  28022. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28023. }
  28024. // RenderPipeline
  28025. if (this._postProcessRenderPipelineManager) {
  28026. this._postProcessRenderPipelineManager.update();
  28027. }
  28028. // Multi-cameras?
  28029. if (this.activeCameras.length > 0) {
  28030. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28031. if (cameraIndex > 0) {
  28032. this._engine.clear(null, false, true, true);
  28033. }
  28034. this._processSubCameras(this.activeCameras[cameraIndex]);
  28035. }
  28036. }
  28037. else {
  28038. if (!this.activeCamera) {
  28039. throw new Error("No camera defined");
  28040. }
  28041. this._processSubCameras(this.activeCamera);
  28042. }
  28043. // Intersection checks
  28044. this._checkIntersections();
  28045. // Update the audio listener attached to the camera
  28046. if (BABYLON.AudioEngine) {
  28047. this._updateAudioParameters();
  28048. }
  28049. // After render
  28050. if (this.afterRender) {
  28051. this.afterRender();
  28052. }
  28053. this.onAfterRenderObservable.notifyObservers(this);
  28054. // Cleaning
  28055. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28056. var data = this._toBeDisposed.data[index];
  28057. if (data) {
  28058. data.dispose();
  28059. }
  28060. this._toBeDisposed[index] = null;
  28061. }
  28062. this._toBeDisposed.reset();
  28063. if (this.dumpNextRenderTargets) {
  28064. this.dumpNextRenderTargets = false;
  28065. }
  28066. this._activeBones.addCount(0, true);
  28067. this._activeIndices.addCount(0, true);
  28068. this._activeParticles.addCount(0, true);
  28069. };
  28070. Scene.prototype._updateAudioParameters = function () {
  28071. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28072. return;
  28073. }
  28074. var listeningCamera;
  28075. var audioEngine = BABYLON.Engine.audioEngine;
  28076. if (this.activeCameras.length > 0) {
  28077. listeningCamera = this.activeCameras[0];
  28078. }
  28079. else {
  28080. listeningCamera = this.activeCamera;
  28081. }
  28082. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28083. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28084. // for VR cameras
  28085. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28086. listeningCamera = listeningCamera.rigCameras[0];
  28087. }
  28088. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28089. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28090. cameraDirection.normalize();
  28091. // To avoid some errors on GearVR
  28092. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28093. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28094. }
  28095. var i;
  28096. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28097. var sound = this.mainSoundTrack.soundCollection[i];
  28098. if (sound.useCustomAttenuation) {
  28099. sound.updateDistanceFromListener();
  28100. }
  28101. }
  28102. for (i = 0; i < this.soundTracks.length; i++) {
  28103. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28104. sound = this.soundTracks[i].soundCollection[j];
  28105. if (sound.useCustomAttenuation) {
  28106. sound.updateDistanceFromListener();
  28107. }
  28108. }
  28109. }
  28110. }
  28111. };
  28112. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28113. // Audio
  28114. /**
  28115. * Gets or sets if audio support is enabled
  28116. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28117. */
  28118. get: function () {
  28119. return this._audioEnabled;
  28120. },
  28121. set: function (value) {
  28122. this._audioEnabled = value;
  28123. if (BABYLON.AudioEngine) {
  28124. if (this._audioEnabled) {
  28125. this._enableAudio();
  28126. }
  28127. else {
  28128. this._disableAudio();
  28129. }
  28130. }
  28131. },
  28132. enumerable: true,
  28133. configurable: true
  28134. });
  28135. Scene.prototype._disableAudio = function () {
  28136. var i;
  28137. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28138. this.mainSoundTrack.soundCollection[i].pause();
  28139. }
  28140. for (i = 0; i < this.soundTracks.length; i++) {
  28141. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28142. this.soundTracks[i].soundCollection[j].pause();
  28143. }
  28144. }
  28145. };
  28146. Scene.prototype._enableAudio = function () {
  28147. var i;
  28148. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28149. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28150. this.mainSoundTrack.soundCollection[i].play();
  28151. }
  28152. }
  28153. for (i = 0; i < this.soundTracks.length; i++) {
  28154. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28155. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28156. this.soundTracks[i].soundCollection[j].play();
  28157. }
  28158. }
  28159. }
  28160. };
  28161. Object.defineProperty(Scene.prototype, "headphone", {
  28162. /**
  28163. * Gets or sets if audio will be output to headphones
  28164. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28165. */
  28166. get: function () {
  28167. return this._headphone;
  28168. },
  28169. set: function (value) {
  28170. this._headphone = value;
  28171. if (BABYLON.AudioEngine) {
  28172. if (this._headphone) {
  28173. this._switchAudioModeForHeadphones();
  28174. }
  28175. else {
  28176. this._switchAudioModeForNormalSpeakers();
  28177. }
  28178. }
  28179. },
  28180. enumerable: true,
  28181. configurable: true
  28182. });
  28183. Scene.prototype._switchAudioModeForHeadphones = function () {
  28184. this.mainSoundTrack.switchPanningModelToHRTF();
  28185. for (var i = 0; i < this.soundTracks.length; i++) {
  28186. this.soundTracks[i].switchPanningModelToHRTF();
  28187. }
  28188. };
  28189. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28190. this.mainSoundTrack.switchPanningModelToEqualPower();
  28191. for (var i = 0; i < this.soundTracks.length; i++) {
  28192. this.soundTracks[i].switchPanningModelToEqualPower();
  28193. }
  28194. };
  28195. /**
  28196. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28197. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28198. * @returns the created depth renderer
  28199. */
  28200. Scene.prototype.enableDepthRenderer = function (camera) {
  28201. camera = camera || this.activeCamera;
  28202. if (!camera) {
  28203. throw "No camera available to enable depth renderer";
  28204. }
  28205. if (!this._depthRenderer[camera.id]) {
  28206. var textureType = 0;
  28207. if (this._engine.getCaps().textureHalfFloatRender) {
  28208. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28209. }
  28210. else if (this._engine.getCaps().textureFloatRender) {
  28211. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28212. }
  28213. else {
  28214. throw "Depth renderer does not support int texture type";
  28215. }
  28216. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28217. }
  28218. return this._depthRenderer[camera.id];
  28219. };
  28220. /**
  28221. * Disables a depth renderer for a given camera
  28222. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28223. */
  28224. Scene.prototype.disableDepthRenderer = function (camera) {
  28225. camera = camera || this.activeCamera;
  28226. if (!camera || !this._depthRenderer[camera.id]) {
  28227. return;
  28228. }
  28229. this._depthRenderer[camera.id].dispose();
  28230. delete this._depthRenderer[camera.id];
  28231. };
  28232. /**
  28233. * Enables a GeometryBufferRender and associates it with the scene
  28234. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28235. * @returns the GeometryBufferRenderer
  28236. */
  28237. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28238. if (ratio === void 0) { ratio = 1; }
  28239. if (this._geometryBufferRenderer) {
  28240. return this._geometryBufferRenderer;
  28241. }
  28242. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28243. if (!this._geometryBufferRenderer.isSupported) {
  28244. this._geometryBufferRenderer = null;
  28245. }
  28246. return this._geometryBufferRenderer;
  28247. };
  28248. /**
  28249. * Disables the GeometryBufferRender associated with the scene
  28250. */
  28251. Scene.prototype.disableGeometryBufferRenderer = function () {
  28252. if (!this._geometryBufferRenderer) {
  28253. return;
  28254. }
  28255. this._geometryBufferRenderer.dispose();
  28256. this._geometryBufferRenderer = null;
  28257. };
  28258. /**
  28259. * Freeze all materials
  28260. * A frozen material will not be updatable but should be faster to render
  28261. */
  28262. Scene.prototype.freezeMaterials = function () {
  28263. for (var i = 0; i < this.materials.length; i++) {
  28264. this.materials[i].freeze();
  28265. }
  28266. };
  28267. /**
  28268. * Unfreeze all materials
  28269. * A frozen material will not be updatable but should be faster to render
  28270. */
  28271. Scene.prototype.unfreezeMaterials = function () {
  28272. for (var i = 0; i < this.materials.length; i++) {
  28273. this.materials[i].unfreeze();
  28274. }
  28275. };
  28276. /**
  28277. * Releases all held ressources
  28278. */
  28279. Scene.prototype.dispose = function () {
  28280. this.beforeRender = null;
  28281. this.afterRender = null;
  28282. this.skeletons = [];
  28283. this.morphTargetManagers = [];
  28284. this.importedMeshesFiles = new Array();
  28285. this.stopAllAnimations();
  28286. this.resetCachedMaterial();
  28287. for (var key in this._depthRenderer) {
  28288. this._depthRenderer[key].dispose();
  28289. }
  28290. if (this._gamepadManager) {
  28291. this._gamepadManager.dispose();
  28292. this._gamepadManager = null;
  28293. }
  28294. // Smart arrays
  28295. if (this.activeCamera) {
  28296. this.activeCamera._activeMeshes.dispose();
  28297. this.activeCamera = null;
  28298. }
  28299. this._activeMeshes.dispose();
  28300. this._renderingManager.dispose();
  28301. this._processedMaterials.dispose();
  28302. this._activeParticleSystems.dispose();
  28303. this._activeSkeletons.dispose();
  28304. this._softwareSkinnedMeshes.dispose();
  28305. this._renderTargets.dispose();
  28306. this._registeredForLateAnimationBindings.dispose();
  28307. if (this._boundingBoxRenderer) {
  28308. this._boundingBoxRenderer.dispose();
  28309. }
  28310. this._meshesForIntersections.dispose();
  28311. this._toBeDisposed.dispose();
  28312. // Abort active requests
  28313. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28314. var request = _a[_i];
  28315. request.abort();
  28316. }
  28317. // Debug layer
  28318. if (this._debugLayer) {
  28319. this._debugLayer.hide();
  28320. }
  28321. // Events
  28322. this.onDisposeObservable.notifyObservers(this);
  28323. this.onDisposeObservable.clear();
  28324. this.onBeforeRenderObservable.clear();
  28325. this.onAfterRenderObservable.clear();
  28326. this.onBeforeRenderTargetsRenderObservable.clear();
  28327. this.onAfterRenderTargetsRenderObservable.clear();
  28328. this.onAfterStepObservable.clear();
  28329. this.onBeforeStepObservable.clear();
  28330. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28331. this.onAfterActiveMeshesEvaluationObservable.clear();
  28332. this.onBeforeParticlesRenderingObservable.clear();
  28333. this.onAfterParticlesRenderingObservable.clear();
  28334. this.onBeforeSpritesRenderingObservable.clear();
  28335. this.onAfterSpritesRenderingObservable.clear();
  28336. this.onBeforeDrawPhaseObservable.clear();
  28337. this.onAfterDrawPhaseObservable.clear();
  28338. this.onBeforePhysicsObservable.clear();
  28339. this.onAfterPhysicsObservable.clear();
  28340. this.onBeforeAnimationsObservable.clear();
  28341. this.onAfterAnimationsObservable.clear();
  28342. this.onDataLoadedObservable.clear();
  28343. this.detachControl();
  28344. // Release sounds & sounds tracks
  28345. if (BABYLON.AudioEngine) {
  28346. this.disposeSounds();
  28347. }
  28348. // VR Helper
  28349. if (this.VRHelper) {
  28350. this.VRHelper.dispose();
  28351. }
  28352. // Detach cameras
  28353. var canvas = this._engine.getRenderingCanvas();
  28354. if (canvas) {
  28355. var index;
  28356. for (index = 0; index < this.cameras.length; index++) {
  28357. this.cameras[index].detachControl(canvas);
  28358. }
  28359. }
  28360. // Release animation groups
  28361. while (this.animationGroups.length) {
  28362. this.animationGroups[0].dispose();
  28363. }
  28364. // Release lights
  28365. while (this.lights.length) {
  28366. this.lights[0].dispose();
  28367. }
  28368. // Release meshes
  28369. while (this.meshes.length) {
  28370. this.meshes[0].dispose(true);
  28371. }
  28372. while (this.transformNodes.length) {
  28373. this.removeTransformNode(this.transformNodes[0]);
  28374. }
  28375. // Release cameras
  28376. while (this.cameras.length) {
  28377. this.cameras[0].dispose();
  28378. }
  28379. // Release materials
  28380. if (this.defaultMaterial) {
  28381. this.defaultMaterial.dispose();
  28382. }
  28383. while (this.multiMaterials.length) {
  28384. this.multiMaterials[0].dispose();
  28385. }
  28386. while (this.materials.length) {
  28387. this.materials[0].dispose();
  28388. }
  28389. // Release particles
  28390. while (this.particleSystems.length) {
  28391. this.particleSystems[0].dispose();
  28392. }
  28393. // Release sprites
  28394. while (this.spriteManagers.length) {
  28395. this.spriteManagers[0].dispose();
  28396. }
  28397. // Release postProcesses
  28398. while (this.postProcesses.length) {
  28399. this.postProcesses[0].dispose();
  28400. }
  28401. // Release layers
  28402. while (this.layers.length) {
  28403. this.layers[0].dispose();
  28404. }
  28405. while (this.effectLayers.length) {
  28406. this.effectLayers[0].dispose();
  28407. }
  28408. // Release textures
  28409. while (this.textures.length) {
  28410. this.textures[0].dispose();
  28411. }
  28412. // Release UBO
  28413. this._sceneUbo.dispose();
  28414. if (this._alternateSceneUbo) {
  28415. this._alternateSceneUbo.dispose();
  28416. }
  28417. // Post-processes
  28418. this.postProcessManager.dispose();
  28419. if (this._postProcessRenderPipelineManager) {
  28420. this._postProcessRenderPipelineManager.dispose();
  28421. }
  28422. // Physics
  28423. if (this._physicsEngine) {
  28424. this.disablePhysicsEngine();
  28425. }
  28426. // Remove from engine
  28427. index = this._engine.scenes.indexOf(this);
  28428. if (index > -1) {
  28429. this._engine.scenes.splice(index, 1);
  28430. }
  28431. this._engine.wipeCaches(true);
  28432. this._isDisposed = true;
  28433. };
  28434. Object.defineProperty(Scene.prototype, "isDisposed", {
  28435. /**
  28436. * Gets if the scene is already disposed
  28437. */
  28438. get: function () {
  28439. return this._isDisposed;
  28440. },
  28441. enumerable: true,
  28442. configurable: true
  28443. });
  28444. /**
  28445. * Releases sounds & soundtracks
  28446. */
  28447. Scene.prototype.disposeSounds = function () {
  28448. if (!this._mainSoundTrack) {
  28449. return;
  28450. }
  28451. this.mainSoundTrack.dispose();
  28452. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28453. this.soundTracks[scIndex].dispose();
  28454. }
  28455. };
  28456. /**
  28457. * Call this function to reduce memory footprint of the scene.
  28458. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28459. */
  28460. Scene.prototype.clearCachedVertexData = function () {
  28461. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28462. var mesh = this.meshes[meshIndex];
  28463. var geometry = mesh.geometry;
  28464. if (geometry) {
  28465. geometry._indices = [];
  28466. for (var vbName in geometry._vertexBuffers) {
  28467. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28468. continue;
  28469. }
  28470. geometry._vertexBuffers[vbName]._buffer._data = null;
  28471. }
  28472. }
  28473. }
  28474. };
  28475. /**
  28476. * This function will remove the local cached buffer data from texture.
  28477. * It will save memory but will prevent the texture from being rebuilt
  28478. */
  28479. Scene.prototype.cleanCachedTextureBuffer = function () {
  28480. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28481. var baseTexture = _a[_i];
  28482. var buffer = baseTexture._buffer;
  28483. if (buffer) {
  28484. baseTexture._buffer = null;
  28485. }
  28486. }
  28487. };
  28488. // Octrees
  28489. /**
  28490. * Get the world extend vectors with an optional filter
  28491. *
  28492. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28493. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28494. */
  28495. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28496. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28497. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28498. filterPredicate = filterPredicate || (function () { return true; });
  28499. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28500. mesh.computeWorldMatrix(true);
  28501. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28502. return;
  28503. }
  28504. var boundingInfo = mesh.getBoundingInfo();
  28505. var minBox = boundingInfo.boundingBox.minimumWorld;
  28506. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28507. BABYLON.Tools.CheckExtends(minBox, min, max);
  28508. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28509. });
  28510. return {
  28511. min: min,
  28512. max: max
  28513. };
  28514. };
  28515. /**
  28516. * Creates or updates the octree used to boost selection (picking)
  28517. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28518. * @param maxCapacity defines the maximum capacity per leaf
  28519. * @param maxDepth defines the maximum depth of the octree
  28520. * @returns an octree of AbstractMesh
  28521. */
  28522. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28523. if (maxCapacity === void 0) { maxCapacity = 64; }
  28524. if (maxDepth === void 0) { maxDepth = 2; }
  28525. if (!this._selectionOctree) {
  28526. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28527. }
  28528. var worldExtends = this.getWorldExtends();
  28529. // Update octree
  28530. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28531. return this._selectionOctree;
  28532. };
  28533. // Picking
  28534. /**
  28535. * Creates a ray that can be used to pick in the scene
  28536. * @param x defines the x coordinate of the origin (on-screen)
  28537. * @param y defines the y coordinate of the origin (on-screen)
  28538. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28539. * @param camera defines the camera to use for the picking
  28540. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28541. * @returns a Ray
  28542. */
  28543. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28544. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28545. var result = BABYLON.Ray.Zero();
  28546. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28547. return result;
  28548. };
  28549. /**
  28550. * Creates a ray that can be used to pick in the scene
  28551. * @param x defines the x coordinate of the origin (on-screen)
  28552. * @param y defines the y coordinate of the origin (on-screen)
  28553. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28554. * @param result defines the ray where to store the picking ray
  28555. * @param camera defines the camera to use for the picking
  28556. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28557. * @returns the current scene
  28558. */
  28559. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28560. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28561. var engine = this._engine;
  28562. if (!camera) {
  28563. if (!this.activeCamera)
  28564. throw new Error("Active camera not set");
  28565. camera = this.activeCamera;
  28566. }
  28567. var cameraViewport = camera.viewport;
  28568. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28569. // Moving coordinates to local viewport world
  28570. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28571. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28572. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28573. return this;
  28574. };
  28575. /**
  28576. * Creates a ray that can be used to pick in the scene
  28577. * @param x defines the x coordinate of the origin (on-screen)
  28578. * @param y defines the y coordinate of the origin (on-screen)
  28579. * @param camera defines the camera to use for the picking
  28580. * @returns a Ray
  28581. */
  28582. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28583. var result = BABYLON.Ray.Zero();
  28584. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28585. return result;
  28586. };
  28587. /**
  28588. * Creates a ray that can be used to pick in the scene
  28589. * @param x defines the x coordinate of the origin (on-screen)
  28590. * @param y defines the y coordinate of the origin (on-screen)
  28591. * @param result defines the ray where to store the picking ray
  28592. * @param camera defines the camera to use for the picking
  28593. * @returns the current scene
  28594. */
  28595. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28596. if (!BABYLON.PickingInfo) {
  28597. return this;
  28598. }
  28599. var engine = this._engine;
  28600. if (!camera) {
  28601. if (!this.activeCamera)
  28602. throw new Error("Active camera not set");
  28603. camera = this.activeCamera;
  28604. }
  28605. var cameraViewport = camera.viewport;
  28606. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28607. var identity = BABYLON.Matrix.Identity();
  28608. // Moving coordinates to local viewport world
  28609. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28610. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28611. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28612. return this;
  28613. };
  28614. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28615. if (!BABYLON.PickingInfo) {
  28616. return null;
  28617. }
  28618. var pickingInfo = null;
  28619. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28620. var mesh = this.meshes[meshIndex];
  28621. if (predicate) {
  28622. if (!predicate(mesh)) {
  28623. continue;
  28624. }
  28625. }
  28626. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28627. continue;
  28628. }
  28629. var world = mesh.getWorldMatrix();
  28630. var ray = rayFunction(world);
  28631. var result = mesh.intersects(ray, fastCheck);
  28632. if (!result || !result.hit)
  28633. continue;
  28634. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28635. continue;
  28636. pickingInfo = result;
  28637. if (fastCheck) {
  28638. break;
  28639. }
  28640. }
  28641. return pickingInfo || new BABYLON.PickingInfo();
  28642. };
  28643. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28644. if (!BABYLON.PickingInfo) {
  28645. return null;
  28646. }
  28647. var pickingInfos = new Array();
  28648. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28649. var mesh = this.meshes[meshIndex];
  28650. if (predicate) {
  28651. if (!predicate(mesh)) {
  28652. continue;
  28653. }
  28654. }
  28655. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28656. continue;
  28657. }
  28658. var world = mesh.getWorldMatrix();
  28659. var ray = rayFunction(world);
  28660. var result = mesh.intersects(ray, false);
  28661. if (!result || !result.hit)
  28662. continue;
  28663. pickingInfos.push(result);
  28664. }
  28665. return pickingInfos;
  28666. };
  28667. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28668. if (!BABYLON.PickingInfo) {
  28669. return null;
  28670. }
  28671. var pickingInfo = null;
  28672. if (!camera) {
  28673. if (!this.activeCamera) {
  28674. return null;
  28675. }
  28676. camera = this.activeCamera;
  28677. }
  28678. if (this.spriteManagers.length > 0) {
  28679. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28680. var spriteManager = this.spriteManagers[spriteIndex];
  28681. if (!spriteManager.isPickable) {
  28682. continue;
  28683. }
  28684. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28685. if (!result || !result.hit)
  28686. continue;
  28687. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28688. continue;
  28689. pickingInfo = result;
  28690. if (fastCheck) {
  28691. break;
  28692. }
  28693. }
  28694. }
  28695. return pickingInfo || new BABYLON.PickingInfo();
  28696. };
  28697. /** Launch a ray to try to pick a mesh in the scene
  28698. * @param x position on screen
  28699. * @param y position on screen
  28700. * @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
  28701. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28702. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28703. * @returns a PickingInfo
  28704. */
  28705. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28706. var _this = this;
  28707. if (!BABYLON.PickingInfo) {
  28708. return null;
  28709. }
  28710. var result = this._internalPick(function (world) {
  28711. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28712. return _this._tempPickingRay;
  28713. }, predicate, fastCheck);
  28714. if (result) {
  28715. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28716. }
  28717. return result;
  28718. };
  28719. /** Launch a ray to try to pick a sprite in the scene
  28720. * @param x position on screen
  28721. * @param y position on screen
  28722. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28723. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28724. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28725. * @returns a PickingInfo
  28726. */
  28727. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28728. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28729. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28730. };
  28731. /** Use the given ray to pick a mesh in the scene
  28732. * @param ray The ray to use to pick meshes
  28733. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28734. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28735. * @returns a PickingInfo
  28736. */
  28737. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28738. var _this = this;
  28739. var result = this._internalPick(function (world) {
  28740. if (!_this._pickWithRayInverseMatrix) {
  28741. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28742. }
  28743. world.invertToRef(_this._pickWithRayInverseMatrix);
  28744. if (!_this._cachedRayForTransform) {
  28745. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28746. }
  28747. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28748. return _this._cachedRayForTransform;
  28749. }, predicate, fastCheck);
  28750. if (result) {
  28751. result.ray = ray;
  28752. }
  28753. return result;
  28754. };
  28755. /**
  28756. * Launch a ray to try to pick a mesh in the scene
  28757. * @param x X position on screen
  28758. * @param y Y position on screen
  28759. * @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
  28760. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28761. * @returns an array of PickingInfo
  28762. */
  28763. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28764. var _this = this;
  28765. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28766. };
  28767. /**
  28768. * Launch a ray to try to pick a mesh in the scene
  28769. * @param ray Ray to use
  28770. * @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
  28771. * @returns an array of PickingInfo
  28772. */
  28773. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28774. var _this = this;
  28775. return this._internalMultiPick(function (world) {
  28776. if (!_this._pickWithRayInverseMatrix) {
  28777. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28778. }
  28779. world.invertToRef(_this._pickWithRayInverseMatrix);
  28780. if (!_this._cachedRayForTransform) {
  28781. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28782. }
  28783. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28784. return _this._cachedRayForTransform;
  28785. }, predicate);
  28786. };
  28787. /**
  28788. * Force the value of meshUnderPointer
  28789. * @param mesh defines the mesh to use
  28790. */
  28791. Scene.prototype.setPointerOverMesh = function (mesh) {
  28792. if (this._pointerOverMesh === mesh) {
  28793. return;
  28794. }
  28795. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28796. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28797. }
  28798. this._pointerOverMesh = mesh;
  28799. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28800. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28801. }
  28802. };
  28803. /**
  28804. * Gets the mesh under the pointer
  28805. * @returns a Mesh or null if no mesh is under the pointer
  28806. */
  28807. Scene.prototype.getPointerOverMesh = function () {
  28808. return this._pointerOverMesh;
  28809. };
  28810. /**
  28811. * Force the sprite under the pointer
  28812. * @param sprite defines the sprite to use
  28813. */
  28814. Scene.prototype.setPointerOverSprite = function (sprite) {
  28815. if (this._pointerOverSprite === sprite) {
  28816. return;
  28817. }
  28818. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28819. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28820. }
  28821. this._pointerOverSprite = sprite;
  28822. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28823. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28824. }
  28825. };
  28826. /**
  28827. * Gets the sprite under the pointer
  28828. * @returns a Sprite or null if no sprite is under the pointer
  28829. */
  28830. Scene.prototype.getPointerOverSprite = function () {
  28831. return this._pointerOverSprite;
  28832. };
  28833. // Physics
  28834. /**
  28835. * Gets the current physics engine
  28836. * @returns a PhysicsEngine or null if none attached
  28837. */
  28838. Scene.prototype.getPhysicsEngine = function () {
  28839. return this._physicsEngine;
  28840. };
  28841. /**
  28842. * Enables physics to the current scene
  28843. * @param gravity defines the scene's gravity for the physics engine
  28844. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28845. * @return a boolean indicating if the physics engine was initialized
  28846. */
  28847. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28848. if (gravity === void 0) { gravity = null; }
  28849. if (this._physicsEngine) {
  28850. return true;
  28851. }
  28852. try {
  28853. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28854. return true;
  28855. }
  28856. catch (e) {
  28857. BABYLON.Tools.Error(e.message);
  28858. return false;
  28859. }
  28860. };
  28861. /**
  28862. * Disables and disposes the physics engine associated with the scene
  28863. */
  28864. Scene.prototype.disablePhysicsEngine = function () {
  28865. if (!this._physicsEngine) {
  28866. return;
  28867. }
  28868. this._physicsEngine.dispose();
  28869. this._physicsEngine = null;
  28870. };
  28871. /**
  28872. * Gets a boolean indicating if there is an active physics engine
  28873. * @returns a boolean indicating if there is an active physics engine
  28874. */
  28875. Scene.prototype.isPhysicsEnabled = function () {
  28876. return this._physicsEngine !== undefined;
  28877. };
  28878. /**
  28879. * Deletes a physics compound impostor
  28880. * @param compound defines the compound to delete
  28881. */
  28882. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28883. var mesh = compound.parts[0].mesh;
  28884. if (mesh.physicsImpostor) {
  28885. mesh.physicsImpostor.dispose( /*true*/);
  28886. mesh.physicsImpostor = null;
  28887. }
  28888. };
  28889. // Misc.
  28890. /** @hidden */
  28891. Scene.prototype._rebuildGeometries = function () {
  28892. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28893. var geometry = _a[_i];
  28894. geometry._rebuild();
  28895. }
  28896. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28897. var mesh = _c[_b];
  28898. mesh._rebuild();
  28899. }
  28900. if (this.postProcessManager) {
  28901. this.postProcessManager._rebuild();
  28902. }
  28903. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28904. var layer = _e[_d];
  28905. layer._rebuild();
  28906. }
  28907. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28908. var effectLayer = _g[_f];
  28909. effectLayer._rebuild();
  28910. }
  28911. if (this._boundingBoxRenderer) {
  28912. this._boundingBoxRenderer._rebuild();
  28913. }
  28914. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28915. var system = _j[_h];
  28916. system.rebuild();
  28917. }
  28918. if (this._postProcessRenderPipelineManager) {
  28919. this._postProcessRenderPipelineManager._rebuild();
  28920. }
  28921. };
  28922. /** @hidden */
  28923. Scene.prototype._rebuildTextures = function () {
  28924. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28925. var texture = _a[_i];
  28926. texture._rebuild();
  28927. }
  28928. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28929. };
  28930. /**
  28931. * Creates a default light for the scene.
  28932. * @param replace Whether to replace the existing lights in the scene.
  28933. */
  28934. Scene.prototype.createDefaultLight = function (replace) {
  28935. if (replace === void 0) { replace = false; }
  28936. // Dispose existing light in replace mode.
  28937. if (replace) {
  28938. if (this.lights) {
  28939. for (var i = 0; i < this.lights.length; i++) {
  28940. this.lights[i].dispose();
  28941. }
  28942. }
  28943. }
  28944. // Light
  28945. if (this.lights.length === 0) {
  28946. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28947. }
  28948. };
  28949. /**
  28950. * Creates a default camera for the scene.
  28951. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28952. * @param replace Whether to replace the existing active camera in the scene.
  28953. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28954. */
  28955. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28956. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28957. if (replace === void 0) { replace = false; }
  28958. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28959. // Dispose existing camera in replace mode.
  28960. if (replace) {
  28961. if (this.activeCamera) {
  28962. this.activeCamera.dispose();
  28963. this.activeCamera = null;
  28964. }
  28965. }
  28966. // Camera
  28967. if (!this.activeCamera) {
  28968. var worldExtends = this.getWorldExtends();
  28969. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28970. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28971. var camera;
  28972. var radius = worldSize.length() * 1.5;
  28973. // empty scene scenario!
  28974. if (!isFinite(radius)) {
  28975. radius = 1;
  28976. worldCenter.copyFromFloats(0, 0, 0);
  28977. }
  28978. if (createArcRotateCamera) {
  28979. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28980. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28981. arcRotateCamera.wheelPrecision = 100 / radius;
  28982. camera = arcRotateCamera;
  28983. }
  28984. else {
  28985. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28986. freeCamera.setTarget(worldCenter);
  28987. camera = freeCamera;
  28988. }
  28989. camera.minZ = radius * 0.01;
  28990. camera.maxZ = radius * 1000;
  28991. camera.speed = radius * 0.2;
  28992. this.activeCamera = camera;
  28993. var canvas = this.getEngine().getRenderingCanvas();
  28994. if (attachCameraControls && canvas) {
  28995. camera.attachControl(canvas);
  28996. }
  28997. }
  28998. };
  28999. /**
  29000. * Creates a default camera and a default light
  29001. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29002. * @param replace defines if the camera and/or light will replace the existing ones
  29003. * @param attachCameraControls defines if attachControl will be called on the new camera
  29004. */
  29005. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29006. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29007. if (replace === void 0) { replace = false; }
  29008. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29009. this.createDefaultLight(replace);
  29010. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29011. };
  29012. /**
  29013. * Creates a new sky box
  29014. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29015. * @param environmentTexture defines the texture to use as environment texture
  29016. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29017. * @param scale defines the overall scale of the skybox
  29018. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29019. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29020. * @returns a new mesh holding the sky box
  29021. */
  29022. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29023. if (pbr === void 0) { pbr = false; }
  29024. if (scale === void 0) { scale = 1000; }
  29025. if (blur === void 0) { blur = 0; }
  29026. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29027. if (!environmentTexture) {
  29028. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29029. return null;
  29030. }
  29031. if (setGlobalEnvTexture) {
  29032. if (environmentTexture) {
  29033. this.environmentTexture = environmentTexture;
  29034. }
  29035. }
  29036. // Skybox
  29037. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29038. if (pbr) {
  29039. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29040. hdrSkyboxMaterial.backFaceCulling = false;
  29041. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29042. if (hdrSkyboxMaterial.reflectionTexture) {
  29043. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29044. }
  29045. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29046. hdrSkyboxMaterial.disableLighting = true;
  29047. hdrSkyboxMaterial.twoSidedLighting = true;
  29048. hdrSkybox.infiniteDistance = true;
  29049. hdrSkybox.material = hdrSkyboxMaterial;
  29050. }
  29051. else {
  29052. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29053. skyboxMaterial.backFaceCulling = false;
  29054. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29055. if (skyboxMaterial.reflectionTexture) {
  29056. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29057. }
  29058. skyboxMaterial.disableLighting = true;
  29059. hdrSkybox.infiniteDistance = true;
  29060. hdrSkybox.material = skyboxMaterial;
  29061. }
  29062. return hdrSkybox;
  29063. };
  29064. /**
  29065. * Creates a new environment
  29066. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29067. * @param options defines the options you can use to configure the environment
  29068. * @returns the new EnvironmentHelper
  29069. */
  29070. Scene.prototype.createDefaultEnvironment = function (options) {
  29071. if (BABYLON.EnvironmentHelper) {
  29072. return new BABYLON.EnvironmentHelper(options, this);
  29073. }
  29074. return null;
  29075. };
  29076. /**
  29077. * Creates a new VREXperienceHelper
  29078. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29079. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29080. * @returns a new VREXperienceHelper
  29081. */
  29082. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29083. if (webVROptions === void 0) { webVROptions = {}; }
  29084. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29085. };
  29086. // Tags
  29087. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29088. if (tagsQuery === undefined) {
  29089. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29090. return list;
  29091. }
  29092. var listByTags = [];
  29093. forEach = forEach || (function (item) { return; });
  29094. for (var i in list) {
  29095. var item = list[i];
  29096. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29097. listByTags.push(item);
  29098. forEach(item);
  29099. }
  29100. }
  29101. return listByTags;
  29102. };
  29103. /**
  29104. * Get a list of meshes by tags
  29105. * @param tagsQuery defines the tags query to use
  29106. * @param forEach defines a predicate used to filter results
  29107. * @returns an array of Mesh
  29108. */
  29109. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29110. return this._getByTags(this.meshes, tagsQuery, forEach);
  29111. };
  29112. /**
  29113. * Get a list of cameras by tags
  29114. * @param tagsQuery defines the tags query to use
  29115. * @param forEach defines a predicate used to filter results
  29116. * @returns an array of Camera
  29117. */
  29118. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29119. return this._getByTags(this.cameras, tagsQuery, forEach);
  29120. };
  29121. /**
  29122. * Get a list of lights by tags
  29123. * @param tagsQuery defines the tags query to use
  29124. * @param forEach defines a predicate used to filter results
  29125. * @returns an array of Light
  29126. */
  29127. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29128. return this._getByTags(this.lights, tagsQuery, forEach);
  29129. };
  29130. /**
  29131. * Get a list of materials by tags
  29132. * @param tagsQuery defines the tags query to use
  29133. * @param forEach defines a predicate used to filter results
  29134. * @returns an array of Material
  29135. */
  29136. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29137. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29138. };
  29139. /**
  29140. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29141. * This allowed control for front to back rendering or reversly depending of the special needs.
  29142. *
  29143. * @param renderingGroupId The rendering group id corresponding to its index
  29144. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29145. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29146. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29147. */
  29148. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29149. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29150. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29151. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29152. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29153. };
  29154. /**
  29155. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29156. *
  29157. * @param renderingGroupId The rendering group id corresponding to its index
  29158. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29159. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29160. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29161. */
  29162. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29163. if (depth === void 0) { depth = true; }
  29164. if (stencil === void 0) { stencil = true; }
  29165. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29166. };
  29167. /**
  29168. * Will flag all materials as dirty to trigger new shader compilation
  29169. * @param flag defines the flag used to specify which material part must be marked as dirty
  29170. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29171. */
  29172. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29173. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29174. var material = _a[_i];
  29175. if (predicate && !predicate(material)) {
  29176. continue;
  29177. }
  29178. material.markAsDirty(flag);
  29179. }
  29180. };
  29181. /** @hidden */
  29182. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29183. var _this = this;
  29184. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29185. this._activeRequests.push(request);
  29186. request.onCompleteObservable.add(function (request) {
  29187. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29188. });
  29189. return request;
  29190. };
  29191. /** @hidden */
  29192. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29193. var _this = this;
  29194. return new Promise(function (resolve, reject) {
  29195. _this._loadFile(url, function (data) {
  29196. resolve(data);
  29197. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29198. reject(exception);
  29199. });
  29200. });
  29201. };
  29202. // Statics
  29203. Scene._FOGMODE_NONE = 0;
  29204. Scene._FOGMODE_EXP = 1;
  29205. Scene._FOGMODE_EXP2 = 2;
  29206. Scene._FOGMODE_LINEAR = 3;
  29207. Scene._uniqueIdCounter = 0;
  29208. /**
  29209. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29210. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29211. */
  29212. Scene.MinDeltaTime = 1.0;
  29213. /**
  29214. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29215. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29216. */
  29217. Scene.MaxDeltaTime = 1000.0;
  29218. /** The distance in pixel that you have to move to prevent some events */
  29219. Scene.DragMovementThreshold = 10; // in pixels
  29220. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29221. Scene.LongPressDelay = 500; // in milliseconds
  29222. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29223. Scene.DoubleClickDelay = 300; // in milliseconds
  29224. /** If you need to check double click without raising a single click at first click, enable this flag */
  29225. Scene.ExclusiveDoubleClickMode = false;
  29226. return Scene;
  29227. }());
  29228. BABYLON.Scene = Scene;
  29229. })(BABYLON || (BABYLON = {}));
  29230. //# sourceMappingURL=babylon.scene.js.map
  29231. var BABYLON;
  29232. (function (BABYLON) {
  29233. /**
  29234. * Set of assets to keep when moving a scene into an asset container.
  29235. */
  29236. var KeepAssets = /** @class */ (function () {
  29237. function KeepAssets() {
  29238. /**
  29239. * Cameras to keep.
  29240. */
  29241. this.cameras = new Array();
  29242. /**
  29243. * Lights to keep.
  29244. */
  29245. this.lights = new Array();
  29246. /**
  29247. * Meshes to keep.
  29248. */
  29249. this.meshes = new Array();
  29250. /**
  29251. * Skeletons to keep.
  29252. */
  29253. this.skeletons = new Array();
  29254. /**
  29255. * ParticleSystems to keep.
  29256. */
  29257. this.particleSystems = new Array();
  29258. /**
  29259. * Animations to keep.
  29260. */
  29261. this.animations = new Array();
  29262. /**
  29263. * AnimationGroups to keep.
  29264. */
  29265. this.animationGroups = new Array();
  29266. /**
  29267. * MultiMaterials to keep.
  29268. */
  29269. this.multiMaterials = new Array();
  29270. /**
  29271. * Materials to keep.
  29272. */
  29273. this.materials = new Array();
  29274. /**
  29275. * MorphTargetManagers to keep.
  29276. */
  29277. this.morphTargetManagers = new Array();
  29278. /**
  29279. * Geometries to keep.
  29280. */
  29281. this.geometries = new Array();
  29282. /**
  29283. * TransformNodes to keep.
  29284. */
  29285. this.transformNodes = new Array();
  29286. /**
  29287. * LensFlareSystems to keep.
  29288. */
  29289. this.lensFlareSystems = new Array();
  29290. /**
  29291. * ShadowGenerators to keep.
  29292. */
  29293. this.shadowGenerators = new Array();
  29294. /**
  29295. * ActionManagers to keep.
  29296. */
  29297. this.actionManagers = new Array();
  29298. /**
  29299. * Sounds to keep.
  29300. */
  29301. this.sounds = new Array();
  29302. /**
  29303. * Textures to keep.
  29304. */
  29305. this.textures = new Array();
  29306. /**
  29307. * Effect layers to keep.
  29308. */
  29309. this.effectLayers = new Array();
  29310. }
  29311. return KeepAssets;
  29312. }());
  29313. BABYLON.KeepAssets = KeepAssets;
  29314. /**
  29315. * Container with a set of assets that can be added or removed from a scene.
  29316. */
  29317. var AssetContainer = /** @class */ (function () {
  29318. /**
  29319. * Instantiates an AssetContainer.
  29320. * @param scene The scene the AssetContainer belongs to.
  29321. */
  29322. function AssetContainer(scene) {
  29323. // Objects
  29324. /**
  29325. * Cameras populated in the container.
  29326. */
  29327. this.cameras = new Array();
  29328. /**
  29329. * Lights populated in the container.
  29330. */
  29331. this.lights = new Array();
  29332. /**
  29333. * Meshes populated in the container.
  29334. */
  29335. this.meshes = new Array();
  29336. /**
  29337. * Skeletons populated in the container.
  29338. */
  29339. this.skeletons = new Array();
  29340. /**
  29341. * ParticleSystems populated in the container.
  29342. */
  29343. this.particleSystems = new Array();
  29344. /**
  29345. * Animations populated in the container.
  29346. */
  29347. this.animations = new Array();
  29348. /**
  29349. * AnimationGroups populated in the container.
  29350. */
  29351. this.animationGroups = new Array();
  29352. /**
  29353. * MultiMaterials populated in the container.
  29354. */
  29355. this.multiMaterials = new Array();
  29356. /**
  29357. * Materials populated in the container.
  29358. */
  29359. this.materials = new Array();
  29360. /**
  29361. * MorphTargetManagers populated in the container.
  29362. */
  29363. this.morphTargetManagers = new Array();
  29364. /**
  29365. * Geometries populated in the container.
  29366. */
  29367. this.geometries = new Array();
  29368. /**
  29369. * TransformNodes populated in the container.
  29370. */
  29371. this.transformNodes = new Array();
  29372. /**
  29373. * LensFlareSystems populated in the container.
  29374. */
  29375. this.lensFlareSystems = new Array();
  29376. /**
  29377. * ShadowGenerators populated in the container.
  29378. */
  29379. this.shadowGenerators = new Array();
  29380. /**
  29381. * ActionManagers populated in the container.
  29382. */
  29383. this.actionManagers = new Array();
  29384. /**
  29385. * Sounds populated in the container.
  29386. */
  29387. this.sounds = new Array();
  29388. /**
  29389. * Textures populated in the container.
  29390. */
  29391. this.textures = new Array();
  29392. /**
  29393. * Effect layers populated in the container.
  29394. */
  29395. this.effectLayers = new Array();
  29396. this.scene = scene;
  29397. }
  29398. /**
  29399. * Adds all the assets from the container to the scene.
  29400. */
  29401. AssetContainer.prototype.addAllToScene = function () {
  29402. var _this = this;
  29403. this.cameras.forEach(function (o) {
  29404. _this.scene.addCamera(o);
  29405. });
  29406. this.lights.forEach(function (o) {
  29407. _this.scene.addLight(o);
  29408. });
  29409. this.meshes.forEach(function (o) {
  29410. _this.scene.addMesh(o);
  29411. });
  29412. this.skeletons.forEach(function (o) {
  29413. _this.scene.addSkeleton(o);
  29414. });
  29415. this.particleSystems.forEach(function (o) {
  29416. _this.scene.addParticleSystem(o);
  29417. });
  29418. this.animations.forEach(function (o) {
  29419. _this.scene.addAnimation(o);
  29420. });
  29421. this.animationGroups.forEach(function (o) {
  29422. _this.scene.addAnimationGroup(o);
  29423. });
  29424. this.multiMaterials.forEach(function (o) {
  29425. _this.scene.addMultiMaterial(o);
  29426. });
  29427. this.materials.forEach(function (o) {
  29428. _this.scene.addMaterial(o);
  29429. });
  29430. this.morphTargetManagers.forEach(function (o) {
  29431. _this.scene.addMorphTargetManager(o);
  29432. });
  29433. this.geometries.forEach(function (o) {
  29434. _this.scene.addGeometry(o);
  29435. });
  29436. this.transformNodes.forEach(function (o) {
  29437. _this.scene.addTransformNode(o);
  29438. });
  29439. this.lensFlareSystems.forEach(function (o) {
  29440. _this.scene.addLensFlareSystem(o);
  29441. });
  29442. this.actionManagers.forEach(function (o) {
  29443. _this.scene.addActionManager(o);
  29444. });
  29445. this.sounds.forEach(function (o) {
  29446. o.play();
  29447. o.autoplay = true;
  29448. _this.scene.mainSoundTrack.AddSound(o);
  29449. });
  29450. this.textures.forEach(function (o) {
  29451. _this.scene.addTexture(o);
  29452. });
  29453. this.effectLayers.forEach(function (o) {
  29454. _this.scene.addEffectLayer(o);
  29455. });
  29456. };
  29457. /**
  29458. * Removes all the assets in the container from the scene
  29459. */
  29460. AssetContainer.prototype.removeAllFromScene = function () {
  29461. var _this = this;
  29462. this.cameras.forEach(function (o) {
  29463. _this.scene.removeCamera(o);
  29464. });
  29465. this.lights.forEach(function (o) {
  29466. _this.scene.removeLight(o);
  29467. });
  29468. this.meshes.forEach(function (o) {
  29469. _this.scene.removeMesh(o);
  29470. });
  29471. this.skeletons.forEach(function (o) {
  29472. _this.scene.removeSkeleton(o);
  29473. });
  29474. this.particleSystems.forEach(function (o) {
  29475. _this.scene.removeParticleSystem(o);
  29476. });
  29477. this.animations.forEach(function (o) {
  29478. _this.scene.removeAnimation(o);
  29479. });
  29480. this.animationGroups.forEach(function (o) {
  29481. _this.scene.removeAnimationGroup(o);
  29482. });
  29483. this.multiMaterials.forEach(function (o) {
  29484. _this.scene.removeMultiMaterial(o);
  29485. });
  29486. this.materials.forEach(function (o) {
  29487. _this.scene.removeMaterial(o);
  29488. });
  29489. this.morphTargetManagers.forEach(function (o) {
  29490. _this.scene.removeMorphTargetManager(o);
  29491. });
  29492. this.geometries.forEach(function (o) {
  29493. _this.scene.removeGeometry(o);
  29494. });
  29495. this.transformNodes.forEach(function (o) {
  29496. _this.scene.removeTransformNode(o);
  29497. });
  29498. this.lensFlareSystems.forEach(function (o) {
  29499. _this.scene.removeLensFlareSystem(o);
  29500. });
  29501. this.actionManagers.forEach(function (o) {
  29502. _this.scene.removeActionManager(o);
  29503. });
  29504. this.sounds.forEach(function (o) {
  29505. o.stop();
  29506. o.autoplay = false;
  29507. _this.scene.mainSoundTrack.RemoveSound(o);
  29508. });
  29509. this.textures.forEach(function (o) {
  29510. _this.scene.removeTexture(o);
  29511. });
  29512. this.effectLayers.forEach(function (o) {
  29513. _this.scene.removeEffectLayer(o);
  29514. });
  29515. };
  29516. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29517. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29518. var asset = sourceAssets_1[_i];
  29519. var move = true;
  29520. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29521. var keepAsset = keepAssets_1[_a];
  29522. if (asset === keepAsset) {
  29523. move = false;
  29524. break;
  29525. }
  29526. }
  29527. if (move) {
  29528. targetAssets.push(asset);
  29529. }
  29530. }
  29531. };
  29532. /**
  29533. * Removes all the assets contained in the scene and adds them to the container.
  29534. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29535. */
  29536. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29537. if (keepAssets === undefined) {
  29538. keepAssets = new KeepAssets();
  29539. }
  29540. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29541. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29542. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29543. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29544. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29545. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29546. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29547. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29548. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29549. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29550. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29551. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29552. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29553. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29554. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29555. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29556. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29557. this.removeAllFromScene();
  29558. };
  29559. /**
  29560. * 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.
  29561. * @returns the root mesh
  29562. */
  29563. AssetContainer.prototype.createRootMesh = function () {
  29564. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29565. this.meshes.forEach(function (m) {
  29566. if (!m.parent) {
  29567. rootMesh.addChild(m);
  29568. }
  29569. });
  29570. this.meshes.unshift(rootMesh);
  29571. return rootMesh;
  29572. };
  29573. return AssetContainer;
  29574. }());
  29575. BABYLON.AssetContainer = AssetContainer;
  29576. })(BABYLON || (BABYLON = {}));
  29577. //# sourceMappingURL=babylon.assetContainer.js.map
  29578. var BABYLON;
  29579. (function (BABYLON) {
  29580. var Buffer = /** @class */ (function () {
  29581. /**
  29582. * Constructor
  29583. * @param engine the engine
  29584. * @param data the data to use for this buffer
  29585. * @param updatable whether the data is updatable
  29586. * @param stride the stride (optional)
  29587. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29588. * @param instanced whether the buffer is instanced (optional)
  29589. * @param useBytes set to true if the stride in in bytes (optional)
  29590. */
  29591. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29592. if (stride === void 0) { stride = 0; }
  29593. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29594. if (instanced === void 0) { instanced = false; }
  29595. if (useBytes === void 0) { useBytes = false; }
  29596. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29597. this._engine = engine.getScene().getEngine();
  29598. }
  29599. else {
  29600. this._engine = engine;
  29601. }
  29602. this._updatable = updatable;
  29603. this._instanced = instanced;
  29604. this._data = data;
  29605. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29606. if (!postponeInternalCreation) { // by default
  29607. this.create();
  29608. }
  29609. }
  29610. /**
  29611. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29612. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29613. * @param offset defines offset in the buffer (0 by default)
  29614. * @param size defines the size in floats of attributes (position is 3 for instance)
  29615. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29616. * @param instanced defines if the vertex buffer contains indexed data
  29617. * @param useBytes defines if the offset and stride are in bytes
  29618. * @returns the new vertex buffer
  29619. */
  29620. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29621. if (useBytes === void 0) { useBytes = false; }
  29622. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29623. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29624. // a lot of these parameters are ignored as they are overriden by the buffer
  29625. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29626. };
  29627. // Properties
  29628. Buffer.prototype.isUpdatable = function () {
  29629. return this._updatable;
  29630. };
  29631. Buffer.prototype.getData = function () {
  29632. return this._data;
  29633. };
  29634. Buffer.prototype.getBuffer = function () {
  29635. return this._buffer;
  29636. };
  29637. /**
  29638. * Gets the stride in float32 units (i.e. byte stride / 4).
  29639. * May not be an integer if the byte stride is not divisible by 4.
  29640. * DEPRECATED. Use byteStride instead.
  29641. * @returns the stride in float32 units
  29642. */
  29643. Buffer.prototype.getStrideSize = function () {
  29644. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29645. };
  29646. // Methods
  29647. Buffer.prototype.create = function (data) {
  29648. if (data === void 0) { data = null; }
  29649. if (!data && this._buffer) {
  29650. return; // nothing to do
  29651. }
  29652. data = data || this._data;
  29653. if (!data) {
  29654. return;
  29655. }
  29656. if (!this._buffer) { // create buffer
  29657. if (this._updatable) {
  29658. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29659. this._data = data;
  29660. }
  29661. else {
  29662. this._buffer = this._engine.createVertexBuffer(data);
  29663. }
  29664. }
  29665. else if (this._updatable) { // update buffer
  29666. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29667. this._data = data;
  29668. }
  29669. };
  29670. Buffer.prototype._rebuild = function () {
  29671. this._buffer = null;
  29672. this.create(this._data);
  29673. };
  29674. Buffer.prototype.update = function (data) {
  29675. this.create(data);
  29676. };
  29677. /**
  29678. * Updates the data directly.
  29679. * @param data the new data
  29680. * @param offset the new offset
  29681. * @param vertexCount the vertex count (optional)
  29682. * @param useBytes set to true if the offset is in bytes
  29683. */
  29684. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29685. if (useBytes === void 0) { useBytes = false; }
  29686. if (!this._buffer) {
  29687. return;
  29688. }
  29689. if (this._updatable) { // update buffer
  29690. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29691. this._data = null;
  29692. }
  29693. };
  29694. Buffer.prototype.dispose = function () {
  29695. if (!this._buffer) {
  29696. return;
  29697. }
  29698. if (this._engine._releaseBuffer(this._buffer)) {
  29699. this._buffer = null;
  29700. }
  29701. };
  29702. return Buffer;
  29703. }());
  29704. BABYLON.Buffer = Buffer;
  29705. })(BABYLON || (BABYLON = {}));
  29706. //# sourceMappingURL=babylon.buffer.js.map
  29707. var BABYLON;
  29708. (function (BABYLON) {
  29709. var VertexBuffer = /** @class */ (function () {
  29710. /**
  29711. * Constructor
  29712. * @param engine the engine
  29713. * @param data the data to use for this vertex buffer
  29714. * @param kind the vertex buffer kind
  29715. * @param updatable whether the data is updatable
  29716. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29717. * @param stride the stride (optional)
  29718. * @param instanced whether the buffer is instanced (optional)
  29719. * @param offset the offset of the data (optional)
  29720. * @param size the number of components (optional)
  29721. * @param type the type of the component (optional)
  29722. * @param normalized whether the data contains normalized data (optional)
  29723. * @param useBytes set to true if stride and offset are in bytes (optional)
  29724. */
  29725. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29726. if (normalized === void 0) { normalized = false; }
  29727. if (useBytes === void 0) { useBytes = false; }
  29728. if (data instanceof BABYLON.Buffer) {
  29729. this._buffer = data;
  29730. this._ownsBuffer = false;
  29731. }
  29732. else {
  29733. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29734. this._ownsBuffer = true;
  29735. }
  29736. this._kind = kind;
  29737. if (type == undefined) {
  29738. var data_1 = this.getData();
  29739. this.type = VertexBuffer.FLOAT;
  29740. if (data_1 instanceof Int8Array)
  29741. this.type = VertexBuffer.BYTE;
  29742. else if (data_1 instanceof Uint8Array)
  29743. this.type = VertexBuffer.UNSIGNED_BYTE;
  29744. else if (data_1 instanceof Int16Array)
  29745. this.type = VertexBuffer.SHORT;
  29746. else if (data_1 instanceof Uint16Array)
  29747. this.type = VertexBuffer.UNSIGNED_SHORT;
  29748. else if (data_1 instanceof Int32Array)
  29749. this.type = VertexBuffer.INT;
  29750. else if (data_1 instanceof Uint32Array)
  29751. this.type = VertexBuffer.UNSIGNED_INT;
  29752. }
  29753. else {
  29754. this.type = type;
  29755. }
  29756. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29757. if (useBytes) {
  29758. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29759. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29760. this.byteOffset = offset || 0;
  29761. }
  29762. else {
  29763. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29764. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29765. this.byteOffset = (offset || 0) * typeByteLength;
  29766. }
  29767. this.normalized = normalized;
  29768. this._instanced = instanced !== undefined ? instanced : false;
  29769. this._instanceDivisor = instanced ? 1 : 0;
  29770. }
  29771. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29772. /**
  29773. * Gets or sets the instance divisor when in instanced mode
  29774. */
  29775. get: function () {
  29776. return this._instanceDivisor;
  29777. },
  29778. set: function (value) {
  29779. this._instanceDivisor = value;
  29780. if (value == 0) {
  29781. this._instanced = false;
  29782. }
  29783. else {
  29784. this._instanced = true;
  29785. }
  29786. },
  29787. enumerable: true,
  29788. configurable: true
  29789. });
  29790. VertexBuffer.prototype._rebuild = function () {
  29791. if (!this._buffer) {
  29792. return;
  29793. }
  29794. this._buffer._rebuild();
  29795. };
  29796. /**
  29797. * Returns the kind of the VertexBuffer (string).
  29798. */
  29799. VertexBuffer.prototype.getKind = function () {
  29800. return this._kind;
  29801. };
  29802. // Properties
  29803. /**
  29804. * Boolean : is the VertexBuffer updatable ?
  29805. */
  29806. VertexBuffer.prototype.isUpdatable = function () {
  29807. return this._buffer.isUpdatable();
  29808. };
  29809. /**
  29810. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29811. */
  29812. VertexBuffer.prototype.getData = function () {
  29813. return this._buffer.getData();
  29814. };
  29815. /**
  29816. * Returns the WebGLBuffer associated to the VertexBuffer.
  29817. */
  29818. VertexBuffer.prototype.getBuffer = function () {
  29819. return this._buffer.getBuffer();
  29820. };
  29821. /**
  29822. * Returns the stride as a multiple of the type byte length.
  29823. * DEPRECATED. Use byteStride instead.
  29824. */
  29825. VertexBuffer.prototype.getStrideSize = function () {
  29826. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29827. };
  29828. /**
  29829. * Returns the offset as a multiple of the type byte length.
  29830. * DEPRECATED. Use byteOffset instead.
  29831. */
  29832. VertexBuffer.prototype.getOffset = function () {
  29833. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29834. };
  29835. /**
  29836. * Returns the number of components per vertex attribute (integer).
  29837. */
  29838. VertexBuffer.prototype.getSize = function () {
  29839. return this._size;
  29840. };
  29841. /**
  29842. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29843. */
  29844. VertexBuffer.prototype.getIsInstanced = function () {
  29845. return this._instanced;
  29846. };
  29847. /**
  29848. * Returns the instancing divisor, zero for non-instanced (integer).
  29849. */
  29850. VertexBuffer.prototype.getInstanceDivisor = function () {
  29851. return this._instanceDivisor;
  29852. };
  29853. // Methods
  29854. /**
  29855. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29856. * Returns the created WebGLBuffer.
  29857. */
  29858. VertexBuffer.prototype.create = function (data) {
  29859. return this._buffer.create(data);
  29860. };
  29861. /**
  29862. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29863. * This function will create a new buffer if the current one is not updatable
  29864. * Returns the updated WebGLBuffer.
  29865. */
  29866. VertexBuffer.prototype.update = function (data) {
  29867. return this._buffer.update(data);
  29868. };
  29869. /**
  29870. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29871. * Returns the directly updated WebGLBuffer.
  29872. * @param data the new data
  29873. * @param offset the new offset
  29874. * @param useBytes set to true if the offset is in bytes
  29875. */
  29876. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29877. if (useBytes === void 0) { useBytes = false; }
  29878. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29879. };
  29880. /**
  29881. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29882. */
  29883. VertexBuffer.prototype.dispose = function () {
  29884. if (this._ownsBuffer) {
  29885. this._buffer.dispose();
  29886. }
  29887. };
  29888. /**
  29889. * Enumerates each value of this vertex buffer as numbers.
  29890. * @param count the number of values to enumerate
  29891. * @param callback the callback function called for each value
  29892. */
  29893. VertexBuffer.prototype.forEach = function (count, callback) {
  29894. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29895. };
  29896. Object.defineProperty(VertexBuffer, "PositionKind", {
  29897. get: function () {
  29898. return VertexBuffer._PositionKind;
  29899. },
  29900. enumerable: true,
  29901. configurable: true
  29902. });
  29903. Object.defineProperty(VertexBuffer, "NormalKind", {
  29904. get: function () {
  29905. return VertexBuffer._NormalKind;
  29906. },
  29907. enumerable: true,
  29908. configurable: true
  29909. });
  29910. Object.defineProperty(VertexBuffer, "TangentKind", {
  29911. get: function () {
  29912. return VertexBuffer._TangentKind;
  29913. },
  29914. enumerable: true,
  29915. configurable: true
  29916. });
  29917. Object.defineProperty(VertexBuffer, "UVKind", {
  29918. get: function () {
  29919. return VertexBuffer._UVKind;
  29920. },
  29921. enumerable: true,
  29922. configurable: true
  29923. });
  29924. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29925. get: function () {
  29926. return VertexBuffer._UV2Kind;
  29927. },
  29928. enumerable: true,
  29929. configurable: true
  29930. });
  29931. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29932. get: function () {
  29933. return VertexBuffer._UV3Kind;
  29934. },
  29935. enumerable: true,
  29936. configurable: true
  29937. });
  29938. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29939. get: function () {
  29940. return VertexBuffer._UV4Kind;
  29941. },
  29942. enumerable: true,
  29943. configurable: true
  29944. });
  29945. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29946. get: function () {
  29947. return VertexBuffer._UV5Kind;
  29948. },
  29949. enumerable: true,
  29950. configurable: true
  29951. });
  29952. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29953. get: function () {
  29954. return VertexBuffer._UV6Kind;
  29955. },
  29956. enumerable: true,
  29957. configurable: true
  29958. });
  29959. Object.defineProperty(VertexBuffer, "ColorKind", {
  29960. get: function () {
  29961. return VertexBuffer._ColorKind;
  29962. },
  29963. enumerable: true,
  29964. configurable: true
  29965. });
  29966. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29967. get: function () {
  29968. return VertexBuffer._MatricesIndicesKind;
  29969. },
  29970. enumerable: true,
  29971. configurable: true
  29972. });
  29973. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29974. get: function () {
  29975. return VertexBuffer._MatricesWeightsKind;
  29976. },
  29977. enumerable: true,
  29978. configurable: true
  29979. });
  29980. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29981. get: function () {
  29982. return VertexBuffer._MatricesIndicesExtraKind;
  29983. },
  29984. enumerable: true,
  29985. configurable: true
  29986. });
  29987. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29988. get: function () {
  29989. return VertexBuffer._MatricesWeightsExtraKind;
  29990. },
  29991. enumerable: true,
  29992. configurable: true
  29993. });
  29994. /**
  29995. * Deduces the stride given a kind.
  29996. * @param kind The kind string to deduce
  29997. * @returns The deduced stride
  29998. */
  29999. VertexBuffer.DeduceStride = function (kind) {
  30000. switch (kind) {
  30001. case VertexBuffer.UVKind:
  30002. case VertexBuffer.UV2Kind:
  30003. case VertexBuffer.UV3Kind:
  30004. case VertexBuffer.UV4Kind:
  30005. case VertexBuffer.UV5Kind:
  30006. case VertexBuffer.UV6Kind:
  30007. return 2;
  30008. case VertexBuffer.NormalKind:
  30009. case VertexBuffer.PositionKind:
  30010. return 3;
  30011. case VertexBuffer.ColorKind:
  30012. case VertexBuffer.MatricesIndicesKind:
  30013. case VertexBuffer.MatricesIndicesExtraKind:
  30014. case VertexBuffer.MatricesWeightsKind:
  30015. case VertexBuffer.MatricesWeightsExtraKind:
  30016. case VertexBuffer.TangentKind:
  30017. return 4;
  30018. default:
  30019. throw new Error("Invalid kind '" + kind + "'");
  30020. }
  30021. };
  30022. /**
  30023. * Gets the byte length of the given type.
  30024. * @param type the type
  30025. * @returns the number of bytes
  30026. */
  30027. VertexBuffer.GetTypeByteLength = function (type) {
  30028. switch (type) {
  30029. case VertexBuffer.BYTE:
  30030. case VertexBuffer.UNSIGNED_BYTE:
  30031. return 1;
  30032. case VertexBuffer.SHORT:
  30033. case VertexBuffer.UNSIGNED_SHORT:
  30034. return 2;
  30035. case VertexBuffer.INT:
  30036. case VertexBuffer.FLOAT:
  30037. return 4;
  30038. default:
  30039. throw new Error("Invalid type '" + type + "'");
  30040. }
  30041. };
  30042. /**
  30043. * Enumerates each value of the given parameters as numbers.
  30044. * @param data the data to enumerate
  30045. * @param byteOffset the byte offset of the data
  30046. * @param byteStride the byte stride of the data
  30047. * @param componentCount the number of components per element
  30048. * @param componentType the type of the component
  30049. * @param count the total number of components
  30050. * @param normalized whether the data is normalized
  30051. * @param callback the callback function called for each value
  30052. */
  30053. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30054. if (data instanceof Array) {
  30055. var offset = byteOffset / 4;
  30056. var stride = byteStride / 4;
  30057. for (var index = 0; index < count; index += componentCount) {
  30058. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30059. callback(data[offset + componentIndex], index + componentIndex);
  30060. }
  30061. offset += stride;
  30062. }
  30063. }
  30064. else {
  30065. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30066. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30067. for (var index = 0; index < count; index += componentCount) {
  30068. var componentByteOffset = byteOffset;
  30069. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30070. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30071. callback(value, index + componentIndex);
  30072. componentByteOffset += componentByteLength;
  30073. }
  30074. byteOffset += byteStride;
  30075. }
  30076. }
  30077. };
  30078. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30079. switch (type) {
  30080. case VertexBuffer.BYTE: {
  30081. var value = dataView.getInt8(byteOffset);
  30082. if (normalized) {
  30083. value = Math.max(value / 127, -1);
  30084. }
  30085. return value;
  30086. }
  30087. case VertexBuffer.UNSIGNED_BYTE: {
  30088. var value = dataView.getUint8(byteOffset);
  30089. if (normalized) {
  30090. value = value / 255;
  30091. }
  30092. return value;
  30093. }
  30094. case VertexBuffer.SHORT: {
  30095. var value = dataView.getInt16(byteOffset, true);
  30096. if (normalized) {
  30097. value = Math.max(value / 16383, -1);
  30098. }
  30099. return value;
  30100. }
  30101. case VertexBuffer.UNSIGNED_SHORT: {
  30102. var value = dataView.getUint16(byteOffset, true);
  30103. if (normalized) {
  30104. value = value / 65535;
  30105. }
  30106. return value;
  30107. }
  30108. case VertexBuffer.FLOAT: {
  30109. return dataView.getFloat32(byteOffset, true);
  30110. }
  30111. default: {
  30112. throw new Error("Invalid component type " + type);
  30113. }
  30114. }
  30115. };
  30116. /**
  30117. * The byte type.
  30118. */
  30119. VertexBuffer.BYTE = 5120;
  30120. /**
  30121. * The unsigned byte type.
  30122. */
  30123. VertexBuffer.UNSIGNED_BYTE = 5121;
  30124. /**
  30125. * The short type.
  30126. */
  30127. VertexBuffer.SHORT = 5122;
  30128. /**
  30129. * The unsigned short type.
  30130. */
  30131. VertexBuffer.UNSIGNED_SHORT = 5123;
  30132. /**
  30133. * The integer type.
  30134. */
  30135. VertexBuffer.INT = 5124;
  30136. /**
  30137. * The unsigned integer type.
  30138. */
  30139. VertexBuffer.UNSIGNED_INT = 5125;
  30140. /**
  30141. * The float type.
  30142. */
  30143. VertexBuffer.FLOAT = 5126;
  30144. // Enums
  30145. VertexBuffer._PositionKind = "position";
  30146. VertexBuffer._NormalKind = "normal";
  30147. VertexBuffer._TangentKind = "tangent";
  30148. VertexBuffer._UVKind = "uv";
  30149. VertexBuffer._UV2Kind = "uv2";
  30150. VertexBuffer._UV3Kind = "uv3";
  30151. VertexBuffer._UV4Kind = "uv4";
  30152. VertexBuffer._UV5Kind = "uv5";
  30153. VertexBuffer._UV6Kind = "uv6";
  30154. VertexBuffer._ColorKind = "color";
  30155. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30156. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30157. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30158. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30159. return VertexBuffer;
  30160. }());
  30161. BABYLON.VertexBuffer = VertexBuffer;
  30162. })(BABYLON || (BABYLON = {}));
  30163. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30164. var BABYLON;
  30165. (function (BABYLON) {
  30166. /**
  30167. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30168. */
  30169. var DummyInternalTextureTracker = /** @class */ (function () {
  30170. function DummyInternalTextureTracker() {
  30171. /**
  30172. * Gets or set the previous tracker in the list
  30173. */
  30174. this.previous = null;
  30175. /**
  30176. * Gets or set the next tracker in the list
  30177. */
  30178. this.next = null;
  30179. }
  30180. return DummyInternalTextureTracker;
  30181. }());
  30182. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30183. })(BABYLON || (BABYLON = {}));
  30184. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30185. var BABYLON;
  30186. (function (BABYLON) {
  30187. /**
  30188. * Class used to store data associated with WebGL texture data for the engine
  30189. * This class should not be used directly
  30190. */
  30191. var InternalTexture = /** @class */ (function () {
  30192. /**
  30193. * Creates a new InternalTexture
  30194. * @param engine defines the engine to use
  30195. * @param dataSource defines the type of data that will be used
  30196. */
  30197. function InternalTexture(engine, dataSource) {
  30198. /**
  30199. * Observable called when the texture is loaded
  30200. */
  30201. this.onLoadedObservable = new BABYLON.Observable();
  30202. /**
  30203. * Gets or set the previous tracker in the list
  30204. */
  30205. this.previous = null;
  30206. /**
  30207. * Gets or set the next tracker in the list
  30208. */
  30209. this.next = null;
  30210. // Private
  30211. /** @hidden */
  30212. this._initialSlot = -1;
  30213. /** @hidden */
  30214. this._designatedSlot = -1;
  30215. /** @hidden */
  30216. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30217. /** @hidden */
  30218. this._comparisonFunction = 0;
  30219. /** @hidden */
  30220. this._lodGenerationScale = 0;
  30221. /** @hidden */
  30222. this._lodGenerationOffset = 0;
  30223. /** @hidden */
  30224. this._isRGBD = false;
  30225. /** @hidden */
  30226. this._references = 1;
  30227. this._engine = engine;
  30228. this._dataSource = dataSource;
  30229. this._webGLTexture = engine._createTexture();
  30230. }
  30231. /**
  30232. * Gets the Engine the texture belongs to.
  30233. * @returns The babylon engine
  30234. */
  30235. InternalTexture.prototype.getEngine = function () {
  30236. return this._engine;
  30237. };
  30238. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30239. /**
  30240. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30241. */
  30242. get: function () {
  30243. return this._dataSource;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. /**
  30249. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30250. */
  30251. InternalTexture.prototype.incrementReferences = function () {
  30252. this._references++;
  30253. };
  30254. /**
  30255. * Change the size of the texture (not the size of the content)
  30256. * @param width defines the new width
  30257. * @param height defines the new height
  30258. * @param depth defines the new depth (1 by default)
  30259. */
  30260. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30261. if (depth === void 0) { depth = 1; }
  30262. this.width = width;
  30263. this.height = height;
  30264. this.depth = depth;
  30265. this.baseWidth = width;
  30266. this.baseHeight = height;
  30267. this.baseDepth = depth;
  30268. this._size = width * height * depth;
  30269. };
  30270. /** @hidden */
  30271. InternalTexture.prototype._rebuild = function () {
  30272. var _this = this;
  30273. var proxy;
  30274. this.isReady = false;
  30275. this._cachedCoordinatesMode = null;
  30276. this._cachedWrapU = null;
  30277. this._cachedWrapV = null;
  30278. this._cachedAnisotropicFilteringLevel = null;
  30279. switch (this._dataSource) {
  30280. case InternalTexture.DATASOURCE_TEMP:
  30281. return;
  30282. case InternalTexture.DATASOURCE_URL:
  30283. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30284. _this.isReady = true;
  30285. }, null, this._buffer, undefined, this.format);
  30286. proxy._swapAndDie(this);
  30287. return;
  30288. case InternalTexture.DATASOURCE_RAW:
  30289. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30290. proxy._swapAndDie(this);
  30291. this.isReady = true;
  30292. return;
  30293. case InternalTexture.DATASOURCE_RAW3D:
  30294. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30295. proxy._swapAndDie(this);
  30296. this.isReady = true;
  30297. return;
  30298. case InternalTexture.DATASOURCE_DYNAMIC:
  30299. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30300. proxy._swapAndDie(this);
  30301. // The engine will make sure to update content so no need to flag it as isReady = true
  30302. return;
  30303. case InternalTexture.DATASOURCE_RENDERTARGET:
  30304. var options = new BABYLON.RenderTargetCreationOptions();
  30305. options.generateDepthBuffer = this._generateDepthBuffer;
  30306. options.generateMipMaps = this.generateMipMaps;
  30307. options.generateStencilBuffer = this._generateStencilBuffer;
  30308. options.samplingMode = this.samplingMode;
  30309. options.type = this.type;
  30310. if (this.isCube) {
  30311. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30312. }
  30313. else {
  30314. var size = {
  30315. width: this.width,
  30316. height: this.height
  30317. };
  30318. proxy = this._engine.createRenderTargetTexture(size, options);
  30319. }
  30320. proxy._swapAndDie(this);
  30321. this.isReady = true;
  30322. return;
  30323. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30324. var depthTextureOptions = {
  30325. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30326. comparisonFunction: this._comparisonFunction,
  30327. generateStencil: this._generateStencilBuffer,
  30328. isCube: this.isCube
  30329. };
  30330. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30331. proxy._swapAndDie(this);
  30332. this.isReady = true;
  30333. return;
  30334. case InternalTexture.DATASOURCE_CUBE:
  30335. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30336. _this.isReady = true;
  30337. }, null, this.format, this._extension);
  30338. proxy._swapAndDie(this);
  30339. return;
  30340. case InternalTexture.DATASOURCE_CUBERAW:
  30341. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30342. proxy._swapAndDie(this);
  30343. this.isReady = true;
  30344. return;
  30345. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30346. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30347. if (proxy) {
  30348. proxy._swapAndDie(_this);
  30349. }
  30350. _this.isReady = true;
  30351. }, null, this.format, this._extension);
  30352. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30353. return;
  30354. }
  30355. };
  30356. InternalTexture.prototype._swapAndDie = function (target) {
  30357. target._webGLTexture = this._webGLTexture;
  30358. if (this._framebuffer) {
  30359. target._framebuffer = this._framebuffer;
  30360. }
  30361. if (this._depthStencilBuffer) {
  30362. target._depthStencilBuffer = this._depthStencilBuffer;
  30363. }
  30364. if (this._lodTextureHigh) {
  30365. if (target._lodTextureHigh) {
  30366. target._lodTextureHigh.dispose();
  30367. }
  30368. target._lodTextureHigh = this._lodTextureHigh;
  30369. }
  30370. if (this._lodTextureMid) {
  30371. if (target._lodTextureMid) {
  30372. target._lodTextureMid.dispose();
  30373. }
  30374. target._lodTextureMid = this._lodTextureMid;
  30375. }
  30376. if (this._lodTextureLow) {
  30377. if (target._lodTextureLow) {
  30378. target._lodTextureLow.dispose();
  30379. }
  30380. target._lodTextureLow = this._lodTextureLow;
  30381. }
  30382. var cache = this._engine.getLoadedTexturesCache();
  30383. var index = cache.indexOf(this);
  30384. if (index !== -1) {
  30385. cache.splice(index, 1);
  30386. }
  30387. };
  30388. /**
  30389. * Dispose the current allocated resources
  30390. */
  30391. InternalTexture.prototype.dispose = function () {
  30392. if (!this._webGLTexture) {
  30393. return;
  30394. }
  30395. this._references--;
  30396. if (this._references === 0) {
  30397. this._engine._releaseTexture(this);
  30398. this._webGLTexture = null;
  30399. this.previous = null;
  30400. this.next = null;
  30401. }
  30402. };
  30403. /**
  30404. * The source of the texture data is unknown
  30405. */
  30406. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30407. /**
  30408. * Texture data comes from an URL
  30409. */
  30410. InternalTexture.DATASOURCE_URL = 1;
  30411. /**
  30412. * Texture data is only used for temporary storage
  30413. */
  30414. InternalTexture.DATASOURCE_TEMP = 2;
  30415. /**
  30416. * Texture data comes from raw data (ArrayBuffer)
  30417. */
  30418. InternalTexture.DATASOURCE_RAW = 3;
  30419. /**
  30420. * Texture content is dynamic (video or dynamic texture)
  30421. */
  30422. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30423. /**
  30424. * Texture content is generated by rendering to it
  30425. */
  30426. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30427. /**
  30428. * Texture content is part of a multi render target process
  30429. */
  30430. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30431. /**
  30432. * Texture data comes from a cube data file
  30433. */
  30434. InternalTexture.DATASOURCE_CUBE = 7;
  30435. /**
  30436. * Texture data comes from a raw cube data
  30437. */
  30438. InternalTexture.DATASOURCE_CUBERAW = 8;
  30439. /**
  30440. * Texture data come from a prefiltered cube data file
  30441. */
  30442. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30443. /**
  30444. * Texture content is raw 3D data
  30445. */
  30446. InternalTexture.DATASOURCE_RAW3D = 10;
  30447. /**
  30448. * Texture content is a depth texture
  30449. */
  30450. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30451. return InternalTexture;
  30452. }());
  30453. BABYLON.InternalTexture = InternalTexture;
  30454. })(BABYLON || (BABYLON = {}));
  30455. //# sourceMappingURL=babylon.internalTexture.js.map
  30456. var BABYLON;
  30457. (function (BABYLON) {
  30458. var BaseTexture = /** @class */ (function () {
  30459. function BaseTexture(scene) {
  30460. this._hasAlpha = false;
  30461. this.getAlphaFromRGB = false;
  30462. this.level = 1;
  30463. this.coordinatesIndex = 0;
  30464. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30465. /**
  30466. * | Value | Type | Description |
  30467. * | ----- | ------------------ | ----------- |
  30468. * | 0 | CLAMP_ADDRESSMODE | |
  30469. * | 1 | WRAP_ADDRESSMODE | |
  30470. * | 2 | MIRROR_ADDRESSMODE | |
  30471. */
  30472. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30473. /**
  30474. * | Value | Type | Description |
  30475. * | ----- | ------------------ | ----------- |
  30476. * | 0 | CLAMP_ADDRESSMODE | |
  30477. * | 1 | WRAP_ADDRESSMODE | |
  30478. * | 2 | MIRROR_ADDRESSMODE | |
  30479. */
  30480. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30481. /**
  30482. * | Value | Type | Description |
  30483. * | ----- | ------------------ | ----------- |
  30484. * | 0 | CLAMP_ADDRESSMODE | |
  30485. * | 1 | WRAP_ADDRESSMODE | |
  30486. * | 2 | MIRROR_ADDRESSMODE | |
  30487. */
  30488. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30489. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30490. this.isCube = false;
  30491. this.is3D = false;
  30492. this.gammaSpace = true;
  30493. this.invertZ = false;
  30494. this.lodLevelInAlpha = false;
  30495. this.isRenderTarget = false;
  30496. this.animations = new Array();
  30497. /**
  30498. * An event triggered when the texture is disposed.
  30499. */
  30500. this.onDisposeObservable = new BABYLON.Observable();
  30501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30502. this._cachedSize = BABYLON.Size.Zero();
  30503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30504. if (this._scene) {
  30505. this._scene.textures.push(this);
  30506. }
  30507. this._uid = null;
  30508. }
  30509. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30510. get: function () {
  30511. return this._hasAlpha;
  30512. },
  30513. set: function (value) {
  30514. if (this._hasAlpha === value) {
  30515. return;
  30516. }
  30517. this._hasAlpha = value;
  30518. if (this._scene) {
  30519. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30520. }
  30521. },
  30522. enumerable: true,
  30523. configurable: true
  30524. });
  30525. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30526. get: function () {
  30527. return this._coordinatesMode;
  30528. },
  30529. /**
  30530. * How a texture is mapped.
  30531. *
  30532. * | Value | Type | Description |
  30533. * | ----- | ----------------------------------- | ----------- |
  30534. * | 0 | EXPLICIT_MODE | |
  30535. * | 1 | SPHERICAL_MODE | |
  30536. * | 2 | PLANAR_MODE | |
  30537. * | 3 | CUBIC_MODE | |
  30538. * | 4 | PROJECTION_MODE | |
  30539. * | 5 | SKYBOX_MODE | |
  30540. * | 6 | INVCUBIC_MODE | |
  30541. * | 7 | EQUIRECTANGULAR_MODE | |
  30542. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30543. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30544. */
  30545. set: function (value) {
  30546. if (this._coordinatesMode === value) {
  30547. return;
  30548. }
  30549. this._coordinatesMode = value;
  30550. if (this._scene) {
  30551. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30552. }
  30553. },
  30554. enumerable: true,
  30555. configurable: true
  30556. });
  30557. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30558. /**
  30559. * Gets whether or not the texture contains RGBD data.
  30560. */
  30561. get: function () {
  30562. return this._texture != null && this._texture._isRGBD;
  30563. },
  30564. enumerable: true,
  30565. configurable: true
  30566. });
  30567. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30568. get: function () {
  30569. if (this._texture)
  30570. return this._texture._lodGenerationOffset;
  30571. return 0.0;
  30572. },
  30573. set: function (value) {
  30574. if (this._texture)
  30575. this._texture._lodGenerationOffset = value;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30581. get: function () {
  30582. if (this._texture)
  30583. return this._texture._lodGenerationScale;
  30584. return 0.0;
  30585. },
  30586. set: function (value) {
  30587. if (this._texture)
  30588. this._texture._lodGenerationScale = value;
  30589. },
  30590. enumerable: true,
  30591. configurable: true
  30592. });
  30593. Object.defineProperty(BaseTexture.prototype, "uid", {
  30594. get: function () {
  30595. if (!this._uid) {
  30596. this._uid = BABYLON.Tools.RandomId();
  30597. }
  30598. return this._uid;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. BaseTexture.prototype.toString = function () {
  30604. return this.name;
  30605. };
  30606. BaseTexture.prototype.getClassName = function () {
  30607. return "BaseTexture";
  30608. };
  30609. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30610. set: function (callback) {
  30611. if (this._onDisposeObserver) {
  30612. this.onDisposeObservable.remove(this._onDisposeObserver);
  30613. }
  30614. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30615. },
  30616. enumerable: true,
  30617. configurable: true
  30618. });
  30619. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30620. get: function () {
  30621. return true;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. BaseTexture.prototype.getScene = function () {
  30627. return this._scene;
  30628. };
  30629. BaseTexture.prototype.getTextureMatrix = function () {
  30630. return BABYLON.Matrix.IdentityReadOnly;
  30631. };
  30632. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30633. return BABYLON.Matrix.IdentityReadOnly;
  30634. };
  30635. BaseTexture.prototype.getInternalTexture = function () {
  30636. return this._texture;
  30637. };
  30638. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30639. return !this.isBlocking || this.isReady();
  30640. };
  30641. BaseTexture.prototype.isReady = function () {
  30642. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30643. this.delayLoad();
  30644. return false;
  30645. }
  30646. if (this._texture) {
  30647. return this._texture.isReady;
  30648. }
  30649. return false;
  30650. };
  30651. BaseTexture.prototype.getSize = function () {
  30652. if (this._texture) {
  30653. if (this._texture.width) {
  30654. this._cachedSize.width = this._texture.width;
  30655. this._cachedSize.height = this._texture.height;
  30656. return this._cachedSize;
  30657. }
  30658. if (this._texture._size) {
  30659. this._cachedSize.width = this._texture._size;
  30660. this._cachedSize.height = this._texture._size;
  30661. return this._cachedSize;
  30662. }
  30663. }
  30664. return this._cachedSize;
  30665. };
  30666. BaseTexture.prototype.getBaseSize = function () {
  30667. if (!this.isReady() || !this._texture)
  30668. return BABYLON.Size.Zero();
  30669. if (this._texture._size) {
  30670. return new BABYLON.Size(this._texture._size, this._texture._size);
  30671. }
  30672. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30673. };
  30674. BaseTexture.prototype.scale = function (ratio) {
  30675. };
  30676. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30677. get: function () {
  30678. return false;
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30684. if (!this._scene) {
  30685. return null;
  30686. }
  30687. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30688. for (var index = 0; index < texturesCache.length; index++) {
  30689. var texturesCacheEntry = texturesCache[index];
  30690. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30691. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30692. texturesCacheEntry.incrementReferences();
  30693. return texturesCacheEntry;
  30694. }
  30695. }
  30696. }
  30697. return null;
  30698. };
  30699. BaseTexture.prototype._rebuild = function () {
  30700. };
  30701. BaseTexture.prototype.delayLoad = function () {
  30702. };
  30703. BaseTexture.prototype.clone = function () {
  30704. return null;
  30705. };
  30706. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30707. get: function () {
  30708. if (!this._texture) {
  30709. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30710. }
  30711. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30717. get: function () {
  30718. if (!this._texture) {
  30719. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30720. }
  30721. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. /**
  30727. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30728. * This will returns an RGBA array buffer containing either in values (0-255) or
  30729. * float values (0-1) depending of the underlying buffer type.
  30730. * @param faceIndex The face of the texture to read (in case of cube texture)
  30731. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30732. * @returns The Array buffer containing the pixels data.
  30733. */
  30734. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30735. if (faceIndex === void 0) { faceIndex = 0; }
  30736. if (level === void 0) { level = 0; }
  30737. if (!this._texture) {
  30738. return null;
  30739. }
  30740. var size = this.getSize();
  30741. var width = size.width;
  30742. var height = size.height;
  30743. var scene = this.getScene();
  30744. if (!scene) {
  30745. return null;
  30746. }
  30747. var engine = scene.getEngine();
  30748. if (level != 0) {
  30749. width = width / Math.pow(2, level);
  30750. height = height / Math.pow(2, level);
  30751. width = Math.round(width);
  30752. height = Math.round(height);
  30753. }
  30754. if (this._texture.isCube) {
  30755. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30756. }
  30757. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30758. };
  30759. BaseTexture.prototype.releaseInternalTexture = function () {
  30760. if (this._texture) {
  30761. this._texture.dispose();
  30762. this._texture = null;
  30763. }
  30764. };
  30765. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30766. get: function () {
  30767. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30768. return null;
  30769. }
  30770. if (!this._texture._sphericalPolynomial) {
  30771. this._texture._sphericalPolynomial =
  30772. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30773. }
  30774. return this._texture._sphericalPolynomial;
  30775. },
  30776. set: function (value) {
  30777. if (this._texture) {
  30778. this._texture._sphericalPolynomial = value;
  30779. }
  30780. },
  30781. enumerable: true,
  30782. configurable: true
  30783. });
  30784. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30785. get: function () {
  30786. if (this._texture) {
  30787. return this._texture._lodTextureHigh;
  30788. }
  30789. return null;
  30790. },
  30791. enumerable: true,
  30792. configurable: true
  30793. });
  30794. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30795. get: function () {
  30796. if (this._texture) {
  30797. return this._texture._lodTextureMid;
  30798. }
  30799. return null;
  30800. },
  30801. enumerable: true,
  30802. configurable: true
  30803. });
  30804. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30805. get: function () {
  30806. if (this._texture) {
  30807. return this._texture._lodTextureLow;
  30808. }
  30809. return null;
  30810. },
  30811. enumerable: true,
  30812. configurable: true
  30813. });
  30814. BaseTexture.prototype.dispose = function () {
  30815. if (!this._scene) {
  30816. return;
  30817. }
  30818. // Animations
  30819. this._scene.stopAnimation(this);
  30820. // Remove from scene
  30821. this._scene._removePendingData(this);
  30822. var index = this._scene.textures.indexOf(this);
  30823. if (index >= 0) {
  30824. this._scene.textures.splice(index, 1);
  30825. }
  30826. if (this._texture === undefined) {
  30827. return;
  30828. }
  30829. // Release
  30830. this.releaseInternalTexture();
  30831. // Callback
  30832. this.onDisposeObservable.notifyObservers(this);
  30833. this.onDisposeObservable.clear();
  30834. };
  30835. BaseTexture.prototype.serialize = function () {
  30836. if (!this.name) {
  30837. return null;
  30838. }
  30839. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30840. // Animations
  30841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30842. return serializationObject;
  30843. };
  30844. BaseTexture.WhenAllReady = function (textures, callback) {
  30845. var numRemaining = textures.length;
  30846. if (numRemaining === 0) {
  30847. callback();
  30848. return;
  30849. }
  30850. var _loop_1 = function () {
  30851. texture = textures[i];
  30852. if (texture.isReady()) {
  30853. if (--numRemaining === 0) {
  30854. callback();
  30855. }
  30856. }
  30857. else {
  30858. onLoadObservable = texture.onLoadObservable;
  30859. var onLoadCallback_1 = function () {
  30860. onLoadObservable.removeCallback(onLoadCallback_1);
  30861. if (--numRemaining === 0) {
  30862. callback();
  30863. }
  30864. };
  30865. onLoadObservable.add(onLoadCallback_1);
  30866. }
  30867. };
  30868. var texture, onLoadObservable;
  30869. for (var i = 0; i < textures.length; i++) {
  30870. _loop_1();
  30871. }
  30872. };
  30873. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "name", void 0);
  30877. __decorate([
  30878. BABYLON.serialize("hasAlpha")
  30879. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], BaseTexture.prototype, "level", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30889. __decorate([
  30890. BABYLON.serialize("coordinatesMode")
  30891. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], BaseTexture.prototype, "wrapU", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], BaseTexture.prototype, "wrapV", void 0);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], BaseTexture.prototype, "wrapR", void 0);
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30904. __decorate([
  30905. BABYLON.serialize()
  30906. ], BaseTexture.prototype, "isCube", void 0);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], BaseTexture.prototype, "is3D", void 0);
  30910. __decorate([
  30911. BABYLON.serialize()
  30912. ], BaseTexture.prototype, "gammaSpace", void 0);
  30913. __decorate([
  30914. BABYLON.serialize()
  30915. ], BaseTexture.prototype, "invertZ", void 0);
  30916. __decorate([
  30917. BABYLON.serialize()
  30918. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30919. __decorate([
  30920. BABYLON.serialize()
  30921. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30922. __decorate([
  30923. BABYLON.serialize()
  30924. ], BaseTexture.prototype, "lodGenerationScale", null);
  30925. __decorate([
  30926. BABYLON.serialize()
  30927. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30928. return BaseTexture;
  30929. }());
  30930. BABYLON.BaseTexture = BaseTexture;
  30931. })(BABYLON || (BABYLON = {}));
  30932. //# sourceMappingURL=babylon.baseTexture.js.map
  30933. var BABYLON;
  30934. (function (BABYLON) {
  30935. var Texture = /** @class */ (function (_super) {
  30936. __extends(Texture, _super);
  30937. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30938. if (noMipmap === void 0) { noMipmap = false; }
  30939. if (invertY === void 0) { invertY = true; }
  30940. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30941. if (onLoad === void 0) { onLoad = null; }
  30942. if (onError === void 0) { onError = null; }
  30943. if (buffer === void 0) { buffer = null; }
  30944. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30945. var _this = _super.call(this, scene) || this;
  30946. _this.uOffset = 0;
  30947. _this.vOffset = 0;
  30948. _this.uScale = 1.0;
  30949. _this.vScale = 1.0;
  30950. _this.uAng = 0;
  30951. _this.vAng = 0;
  30952. _this.wAng = 0;
  30953. /**
  30954. * Defines the center of rotation (U)
  30955. */
  30956. _this.uRotationCenter = 0.5;
  30957. /**
  30958. * Defines the center of rotation (V)
  30959. */
  30960. _this.vRotationCenter = 0.5;
  30961. /**
  30962. * Defines the center of rotation (W)
  30963. */
  30964. _this.wRotationCenter = 0.5;
  30965. _this._isBlocking = true;
  30966. _this.name = url || "";
  30967. _this.url = url;
  30968. _this._noMipmap = noMipmap;
  30969. _this._invertY = invertY;
  30970. _this._samplingMode = samplingMode;
  30971. _this._buffer = buffer;
  30972. _this._deleteBuffer = deleteBuffer;
  30973. if (format) {
  30974. _this._format = format;
  30975. }
  30976. scene = _this.getScene();
  30977. if (!scene) {
  30978. return _this;
  30979. }
  30980. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30981. var load = function () {
  30982. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30983. _this.onLoadObservable.notifyObservers(_this);
  30984. }
  30985. if (onLoad) {
  30986. onLoad();
  30987. }
  30988. if (!_this.isBlocking && scene) {
  30989. scene.resetCachedMaterial();
  30990. }
  30991. };
  30992. if (!_this.url) {
  30993. _this._delayedOnLoad = load;
  30994. _this._delayedOnError = onError;
  30995. return _this;
  30996. }
  30997. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30998. if (!_this._texture) {
  30999. if (!scene.useDelayedTextureLoading) {
  31000. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31001. if (deleteBuffer) {
  31002. delete _this._buffer;
  31003. }
  31004. }
  31005. else {
  31006. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31007. _this._delayedOnLoad = load;
  31008. _this._delayedOnError = onError;
  31009. }
  31010. }
  31011. else {
  31012. if (_this._texture.isReady) {
  31013. BABYLON.Tools.SetImmediate(function () { return load(); });
  31014. }
  31015. else {
  31016. _this._texture.onLoadedObservable.add(load);
  31017. }
  31018. }
  31019. return _this;
  31020. }
  31021. Object.defineProperty(Texture.prototype, "noMipmap", {
  31022. get: function () {
  31023. return this._noMipmap;
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Texture.prototype, "isBlocking", {
  31029. get: function () {
  31030. return this._isBlocking;
  31031. },
  31032. set: function (value) {
  31033. this._isBlocking = value;
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Texture.prototype, "samplingMode", {
  31039. get: function () {
  31040. return this._samplingMode;
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. /**
  31046. * Update the url (and optional buffer) of this texture if url was null during construction.
  31047. * @param url the url of the texture
  31048. * @param buffer the buffer of the texture (defaults to null)
  31049. */
  31050. Texture.prototype.updateURL = function (url, buffer) {
  31051. if (buffer === void 0) { buffer = null; }
  31052. if (this.url) {
  31053. throw new Error("URL is already set");
  31054. }
  31055. this.url = url;
  31056. this._buffer = buffer;
  31057. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31058. this.delayLoad();
  31059. };
  31060. Texture.prototype.delayLoad = function () {
  31061. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31062. return;
  31063. }
  31064. var scene = this.getScene();
  31065. if (!scene) {
  31066. return;
  31067. }
  31068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31069. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31070. if (!this._texture) {
  31071. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31072. if (this._deleteBuffer) {
  31073. delete this._buffer;
  31074. }
  31075. }
  31076. else {
  31077. if (this._delayedOnLoad) {
  31078. if (this._texture.isReady) {
  31079. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31080. }
  31081. else {
  31082. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31083. }
  31084. }
  31085. }
  31086. this._delayedOnLoad = null;
  31087. this._delayedOnError = null;
  31088. };
  31089. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31090. if (!this._texture) {
  31091. return;
  31092. }
  31093. var scene = this.getScene();
  31094. if (!scene) {
  31095. return;
  31096. }
  31097. this._samplingMode = samplingMode;
  31098. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31099. };
  31100. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31101. x *= this.uScale;
  31102. y *= this.vScale;
  31103. x -= this.uRotationCenter * this.uScale;
  31104. y -= this.vRotationCenter * this.vScale;
  31105. z -= this.wRotationCenter;
  31106. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31107. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31108. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31109. t.z += this.wRotationCenter;
  31110. };
  31111. Texture.prototype.getTextureMatrix = function () {
  31112. var _this = this;
  31113. if (this.uOffset === this._cachedUOffset &&
  31114. this.vOffset === this._cachedVOffset &&
  31115. this.uScale === this._cachedUScale &&
  31116. this.vScale === this._cachedVScale &&
  31117. this.uAng === this._cachedUAng &&
  31118. this.vAng === this._cachedVAng &&
  31119. this.wAng === this._cachedWAng) {
  31120. return this._cachedTextureMatrix;
  31121. }
  31122. this._cachedUOffset = this.uOffset;
  31123. this._cachedVOffset = this.vOffset;
  31124. this._cachedUScale = this.uScale;
  31125. this._cachedVScale = this.vScale;
  31126. this._cachedUAng = this.uAng;
  31127. this._cachedVAng = this.vAng;
  31128. this._cachedWAng = this.wAng;
  31129. if (!this._cachedTextureMatrix) {
  31130. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31131. this._rowGenerationMatrix = new BABYLON.Matrix();
  31132. this._t0 = BABYLON.Vector3.Zero();
  31133. this._t1 = BABYLON.Vector3.Zero();
  31134. this._t2 = BABYLON.Vector3.Zero();
  31135. }
  31136. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31137. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31138. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31139. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31140. this._t1.subtractInPlace(this._t0);
  31141. this._t2.subtractInPlace(this._t0);
  31142. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31143. this._cachedTextureMatrix.m[0] = this._t1.x;
  31144. this._cachedTextureMatrix.m[1] = this._t1.y;
  31145. this._cachedTextureMatrix.m[2] = this._t1.z;
  31146. this._cachedTextureMatrix.m[4] = this._t2.x;
  31147. this._cachedTextureMatrix.m[5] = this._t2.y;
  31148. this._cachedTextureMatrix.m[6] = this._t2.z;
  31149. this._cachedTextureMatrix.m[8] = this._t0.x;
  31150. this._cachedTextureMatrix.m[9] = this._t0.y;
  31151. this._cachedTextureMatrix.m[10] = this._t0.z;
  31152. var scene = this.getScene();
  31153. if (!scene) {
  31154. return this._cachedTextureMatrix;
  31155. }
  31156. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31157. return mat.hasTexture(_this);
  31158. });
  31159. return this._cachedTextureMatrix;
  31160. };
  31161. Texture.prototype.getReflectionTextureMatrix = function () {
  31162. var _this = this;
  31163. var scene = this.getScene();
  31164. if (!scene) {
  31165. return this._cachedTextureMatrix;
  31166. }
  31167. if (this.uOffset === this._cachedUOffset &&
  31168. this.vOffset === this._cachedVOffset &&
  31169. this.uScale === this._cachedUScale &&
  31170. this.vScale === this._cachedVScale &&
  31171. this.coordinatesMode === this._cachedCoordinatesMode) {
  31172. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31173. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31174. return this._cachedTextureMatrix;
  31175. }
  31176. }
  31177. else {
  31178. return this._cachedTextureMatrix;
  31179. }
  31180. }
  31181. if (!this._cachedTextureMatrix) {
  31182. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31183. }
  31184. if (!this._projectionModeMatrix) {
  31185. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31186. }
  31187. this._cachedUOffset = this.uOffset;
  31188. this._cachedVOffset = this.vOffset;
  31189. this._cachedUScale = this.uScale;
  31190. this._cachedVScale = this.vScale;
  31191. this._cachedCoordinatesMode = this.coordinatesMode;
  31192. switch (this.coordinatesMode) {
  31193. case Texture.PLANAR_MODE:
  31194. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31195. this._cachedTextureMatrix[0] = this.uScale;
  31196. this._cachedTextureMatrix[5] = this.vScale;
  31197. this._cachedTextureMatrix[12] = this.uOffset;
  31198. this._cachedTextureMatrix[13] = this.vOffset;
  31199. break;
  31200. case Texture.PROJECTION_MODE:
  31201. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31202. this._projectionModeMatrix.m[0] = 0.5;
  31203. this._projectionModeMatrix.m[5] = -0.5;
  31204. this._projectionModeMatrix.m[10] = 0.0;
  31205. this._projectionModeMatrix.m[12] = 0.5;
  31206. this._projectionModeMatrix.m[13] = 0.5;
  31207. this._projectionModeMatrix.m[14] = 1.0;
  31208. this._projectionModeMatrix.m[15] = 1.0;
  31209. var projectionMatrix = scene.getProjectionMatrix();
  31210. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31211. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31212. break;
  31213. default:
  31214. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31215. break;
  31216. }
  31217. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31218. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31219. });
  31220. return this._cachedTextureMatrix;
  31221. };
  31222. Texture.prototype.clone = function () {
  31223. var _this = this;
  31224. return BABYLON.SerializationHelper.Clone(function () {
  31225. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31226. }, this);
  31227. };
  31228. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31229. get: function () {
  31230. if (!this._onLoadObservable) {
  31231. this._onLoadObservable = new BABYLON.Observable();
  31232. }
  31233. return this._onLoadObservable;
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Texture.prototype.serialize = function () {
  31239. var serializationObject = _super.prototype.serialize.call(this);
  31240. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31241. serializationObject.base64String = this._buffer;
  31242. serializationObject.name = serializationObject.name.replace("data:", "");
  31243. }
  31244. serializationObject.invertY = this._invertY;
  31245. serializationObject.samplingMode = this.samplingMode;
  31246. return serializationObject;
  31247. };
  31248. Texture.prototype.getClassName = function () {
  31249. return "Texture";
  31250. };
  31251. Texture.prototype.dispose = function () {
  31252. _super.prototype.dispose.call(this);
  31253. if (this._onLoadObservable) {
  31254. this._onLoadObservable.clear();
  31255. this._onLoadObservable = null;
  31256. }
  31257. this._delayedOnLoad = null;
  31258. this._delayedOnError = null;
  31259. };
  31260. // Statics
  31261. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31262. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31263. if (onLoad === void 0) { onLoad = null; }
  31264. if (onError === void 0) { onError = null; }
  31265. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31266. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31267. };
  31268. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31269. if (parsedTexture.customType) {
  31270. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31271. // Update Sampling Mode
  31272. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31273. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31274. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31275. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31276. }
  31277. }
  31278. return parsedCustomTexture;
  31279. }
  31280. if (parsedTexture.isCube) {
  31281. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31282. }
  31283. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31284. return null;
  31285. }
  31286. var texture = BABYLON.SerializationHelper.Parse(function () {
  31287. var generateMipMaps = true;
  31288. if (parsedTexture.noMipmap) {
  31289. generateMipMaps = false;
  31290. }
  31291. if (parsedTexture.mirrorPlane) {
  31292. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31293. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31294. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31295. return mirrorTexture;
  31296. }
  31297. else if (parsedTexture.isRenderTarget) {
  31298. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31299. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31300. return renderTargetTexture;
  31301. }
  31302. else {
  31303. var texture;
  31304. if (parsedTexture.base64String) {
  31305. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31306. }
  31307. else {
  31308. var url = rootUrl + parsedTexture.name;
  31309. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31310. url = parsedTexture.url;
  31311. }
  31312. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31313. }
  31314. return texture;
  31315. }
  31316. }, parsedTexture, scene);
  31317. // Update Sampling Mode
  31318. if (parsedTexture.samplingMode) {
  31319. var sampling = parsedTexture.samplingMode;
  31320. if (texture._samplingMode !== sampling) {
  31321. texture.updateSamplingMode(sampling);
  31322. }
  31323. }
  31324. // Animations
  31325. if (parsedTexture.animations) {
  31326. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31327. var parsedAnimation = parsedTexture.animations[animationIndex];
  31328. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31329. }
  31330. }
  31331. return texture;
  31332. };
  31333. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31334. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31335. if (noMipmap === void 0) { noMipmap = false; }
  31336. if (invertY === void 0) { invertY = true; }
  31337. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31338. if (onLoad === void 0) { onLoad = null; }
  31339. if (onError === void 0) { onError = null; }
  31340. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31341. if (name.substr(0, 5) !== "data:") {
  31342. name = "data:" + name;
  31343. }
  31344. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31345. };
  31346. // Constants
  31347. Texture.NEAREST_SAMPLINGMODE = 1;
  31348. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31349. Texture.BILINEAR_SAMPLINGMODE = 2;
  31350. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31351. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31352. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31353. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31354. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31355. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31356. Texture.NEAREST_LINEAR = 7;
  31357. Texture.NEAREST_NEAREST = 8;
  31358. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31359. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31360. Texture.LINEAR_LINEAR = 11;
  31361. Texture.LINEAR_NEAREST = 12;
  31362. Texture.EXPLICIT_MODE = 0;
  31363. Texture.SPHERICAL_MODE = 1;
  31364. Texture.PLANAR_MODE = 2;
  31365. Texture.CUBIC_MODE = 3;
  31366. Texture.PROJECTION_MODE = 4;
  31367. Texture.SKYBOX_MODE = 5;
  31368. Texture.INVCUBIC_MODE = 6;
  31369. Texture.EQUIRECTANGULAR_MODE = 7;
  31370. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31371. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31372. Texture.CLAMP_ADDRESSMODE = 0;
  31373. Texture.WRAP_ADDRESSMODE = 1;
  31374. Texture.MIRROR_ADDRESSMODE = 2;
  31375. /**
  31376. * 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
  31377. */
  31378. Texture.UseSerializedUrlIfAny = false;
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Texture.prototype, "url", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], Texture.prototype, "uOffset", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Texture.prototype, "vOffset", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Texture.prototype, "uScale", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], Texture.prototype, "vScale", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], Texture.prototype, "uAng", void 0);
  31397. __decorate([
  31398. BABYLON.serialize()
  31399. ], Texture.prototype, "vAng", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], Texture.prototype, "wAng", void 0);
  31403. __decorate([
  31404. BABYLON.serialize()
  31405. ], Texture.prototype, "uRotationCenter", void 0);
  31406. __decorate([
  31407. BABYLON.serialize()
  31408. ], Texture.prototype, "vRotationCenter", void 0);
  31409. __decorate([
  31410. BABYLON.serialize()
  31411. ], Texture.prototype, "wRotationCenter", void 0);
  31412. __decorate([
  31413. BABYLON.serialize()
  31414. ], Texture.prototype, "isBlocking", null);
  31415. return Texture;
  31416. }(BABYLON.BaseTexture));
  31417. BABYLON.Texture = Texture;
  31418. })(BABYLON || (BABYLON = {}));
  31419. //# sourceMappingURL=babylon.texture.js.map
  31420. var BABYLON;
  31421. (function (BABYLON) {
  31422. /**
  31423. * @hidden
  31424. **/
  31425. var _InstancesBatch = /** @class */ (function () {
  31426. function _InstancesBatch() {
  31427. this.mustReturn = false;
  31428. this.visibleInstances = new Array();
  31429. this.renderSelf = new Array();
  31430. }
  31431. return _InstancesBatch;
  31432. }());
  31433. BABYLON._InstancesBatch = _InstancesBatch;
  31434. var Mesh = /** @class */ (function (_super) {
  31435. __extends(Mesh, _super);
  31436. /**
  31437. * @constructor
  31438. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31439. * @param {Scene} scene The scene to add this mesh to.
  31440. * @param {Node} parent The parent of this mesh, if it has one
  31441. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31442. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31443. * When false, achieved by calling a clone(), also passing False.
  31444. * This will make creation of children, recursive.
  31445. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31446. */
  31447. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31448. if (scene === void 0) { scene = null; }
  31449. if (parent === void 0) { parent = null; }
  31450. if (source === void 0) { source = null; }
  31451. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31452. var _this = _super.call(this, name, scene) || this;
  31453. // Events
  31454. /**
  31455. * An event triggered before rendering the mesh
  31456. */
  31457. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31458. /**
  31459. * An event triggered after rendering the mesh
  31460. */
  31461. _this.onAfterRenderObservable = new BABYLON.Observable();
  31462. /**
  31463. * An event triggered before drawing the mesh
  31464. */
  31465. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31466. // Members
  31467. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31468. _this.instances = new Array();
  31469. _this._LODLevels = new Array();
  31470. _this._visibleInstances = {};
  31471. _this._renderIdForInstances = new Array();
  31472. _this._batchCache = new _InstancesBatch();
  31473. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31474. // Use by builder only to know what orientation were the mesh build in.
  31475. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31476. _this.overrideMaterialSideOrientation = null;
  31477. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31478. // Will be used to save a source mesh reference, If any
  31479. _this._source = null;
  31480. scene = _this.getScene();
  31481. if (source) {
  31482. // Geometry
  31483. if (source._geometry) {
  31484. source._geometry.applyToMesh(_this);
  31485. }
  31486. // Deep copy
  31487. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31488. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31489. // Source mesh
  31490. _this._source = source;
  31491. // Metadata
  31492. if (source.metadata && source.metadata.clone) {
  31493. _this.metadata = source.metadata.clone();
  31494. }
  31495. else {
  31496. _this.metadata = source.metadata;
  31497. }
  31498. // Tags
  31499. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31500. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31501. }
  31502. // Parent
  31503. _this.parent = source.parent;
  31504. // Pivot
  31505. _this.setPivotMatrix(source.getPivotMatrix());
  31506. _this.id = name + "." + source.id;
  31507. // Material
  31508. _this.material = source.material;
  31509. var index;
  31510. if (!doNotCloneChildren) {
  31511. // Children
  31512. var directDescendants = source.getDescendants(true);
  31513. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31514. var child = directDescendants[index_1];
  31515. if (child.clone) {
  31516. child.clone(name + "." + child.name, _this);
  31517. }
  31518. }
  31519. }
  31520. // Physics clone
  31521. var physicsEngine = _this.getScene().getPhysicsEngine();
  31522. if (clonePhysicsImpostor && physicsEngine) {
  31523. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31524. if (impostor) {
  31525. _this.physicsImpostor = impostor.clone(_this);
  31526. }
  31527. }
  31528. // Particles
  31529. for (index = 0; index < scene.particleSystems.length; index++) {
  31530. var system = scene.particleSystems[index];
  31531. if (system.emitter === source) {
  31532. system.clone(system.name, _this);
  31533. }
  31534. }
  31535. _this.refreshBoundingInfo();
  31536. _this.computeWorldMatrix(true);
  31537. }
  31538. // Parent
  31539. if (parent !== null) {
  31540. _this.parent = parent;
  31541. }
  31542. return _this;
  31543. }
  31544. Object.defineProperty(Mesh, "FRONTSIDE", {
  31545. /**
  31546. * Mesh side orientation : usually the external or front surface
  31547. */
  31548. get: function () {
  31549. return Mesh._FRONTSIDE;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Mesh, "BACKSIDE", {
  31555. /**
  31556. * Mesh side orientation : usually the internal or back surface
  31557. */
  31558. get: function () {
  31559. return Mesh._BACKSIDE;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31565. /**
  31566. * Mesh side orientation : both internal and external or front and back surfaces
  31567. */
  31568. get: function () {
  31569. return Mesh._DOUBLESIDE;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31575. /**
  31576. * Mesh side orientation : by default, `FRONTSIDE`
  31577. */
  31578. get: function () {
  31579. return Mesh._DEFAULTSIDE;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(Mesh, "NO_CAP", {
  31585. /**
  31586. * Mesh cap setting : no cap
  31587. */
  31588. get: function () {
  31589. return Mesh._NO_CAP;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(Mesh, "CAP_START", {
  31595. /**
  31596. * Mesh cap setting : one cap at the beginning of the mesh
  31597. */
  31598. get: function () {
  31599. return Mesh._CAP_START;
  31600. },
  31601. enumerable: true,
  31602. configurable: true
  31603. });
  31604. Object.defineProperty(Mesh, "CAP_END", {
  31605. /**
  31606. * Mesh cap setting : one cap at the end of the mesh
  31607. */
  31608. get: function () {
  31609. return Mesh._CAP_END;
  31610. },
  31611. enumerable: true,
  31612. configurable: true
  31613. });
  31614. Object.defineProperty(Mesh, "CAP_ALL", {
  31615. /**
  31616. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31617. */
  31618. get: function () {
  31619. return Mesh._CAP_ALL;
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31625. set: function (callback) {
  31626. if (this._onBeforeDrawObserver) {
  31627. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31628. }
  31629. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31635. get: function () {
  31636. return this._morphTargetManager;
  31637. },
  31638. set: function (value) {
  31639. if (this._morphTargetManager === value) {
  31640. return;
  31641. }
  31642. this._morphTargetManager = value;
  31643. this._syncGeometryWithMorphTargetManager();
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. Object.defineProperty(Mesh.prototype, "source", {
  31649. get: function () {
  31650. return this._source;
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31656. get: function () {
  31657. return this._unIndexed;
  31658. },
  31659. set: function (value) {
  31660. if (this._unIndexed !== value) {
  31661. this._unIndexed = value;
  31662. this._markSubMeshesAsAttributesDirty();
  31663. }
  31664. },
  31665. enumerable: true,
  31666. configurable: true
  31667. });
  31668. // Methods
  31669. /**
  31670. * Returns the string "Mesh".
  31671. */
  31672. Mesh.prototype.getClassName = function () {
  31673. return "Mesh";
  31674. };
  31675. /**
  31676. * Returns a string.
  31677. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31678. */
  31679. Mesh.prototype.toString = function (fullDetails) {
  31680. var ret = _super.prototype.toString.call(this, fullDetails);
  31681. ret += ", n vertices: " + this.getTotalVertices();
  31682. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31683. if (this.animations) {
  31684. for (var i = 0; i < this.animations.length; i++) {
  31685. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31686. }
  31687. }
  31688. if (fullDetails) {
  31689. if (this._geometry) {
  31690. var ib = this.getIndices();
  31691. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31692. if (vb && ib) {
  31693. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31694. }
  31695. }
  31696. else {
  31697. ret += ", flat shading: UNKNOWN";
  31698. }
  31699. }
  31700. return ret;
  31701. };
  31702. Mesh.prototype._unBindEffect = function () {
  31703. _super.prototype._unBindEffect.call(this);
  31704. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31705. var instance = _a[_i];
  31706. instance._unBindEffect();
  31707. }
  31708. };
  31709. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31710. /**
  31711. * True if the mesh has some Levels Of Details (LOD).
  31712. * Returns a boolean.
  31713. */
  31714. get: function () {
  31715. return this._LODLevels.length > 0;
  31716. },
  31717. enumerable: true,
  31718. configurable: true
  31719. });
  31720. /**
  31721. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31722. * @returns an array of {BABYLON.MeshLODLevel}
  31723. */
  31724. Mesh.prototype.getLODLevels = function () {
  31725. return this._LODLevels;
  31726. };
  31727. Mesh.prototype._sortLODLevels = function () {
  31728. this._LODLevels.sort(function (a, b) {
  31729. if (a.distance < b.distance) {
  31730. return 1;
  31731. }
  31732. if (a.distance > b.distance) {
  31733. return -1;
  31734. }
  31735. return 0;
  31736. });
  31737. };
  31738. /**
  31739. * Add a mesh as LOD level triggered at the given distance.
  31740. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31741. * @param distance The distance from the center of the object to show this level
  31742. * @param mesh The mesh to be added as LOD level (can be null)
  31743. * @return This mesh (for chaining)
  31744. */
  31745. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31746. if (mesh && mesh._masterMesh) {
  31747. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31748. return this;
  31749. }
  31750. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31751. this._LODLevels.push(level);
  31752. if (mesh) {
  31753. mesh._masterMesh = this;
  31754. }
  31755. this._sortLODLevels();
  31756. return this;
  31757. };
  31758. /**
  31759. * Returns the LOD level mesh at the passed distance or null if not found.
  31760. * It is related to the method `addLODLevel(distance, mesh)`.
  31761. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31762. * Returns an object Mesh or `null`.
  31763. */
  31764. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31765. for (var index = 0; index < this._LODLevels.length; index++) {
  31766. var level = this._LODLevels[index];
  31767. if (level.distance === distance) {
  31768. return level.mesh;
  31769. }
  31770. }
  31771. return null;
  31772. };
  31773. /**
  31774. * Remove a mesh from the LOD array
  31775. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31776. * @param {Mesh} mesh The mesh to be removed.
  31777. * @return {Mesh} This mesh (for chaining)
  31778. */
  31779. Mesh.prototype.removeLODLevel = function (mesh) {
  31780. for (var index = 0; index < this._LODLevels.length; index++) {
  31781. if (this._LODLevels[index].mesh === mesh) {
  31782. this._LODLevels.splice(index, 1);
  31783. if (mesh) {
  31784. mesh._masterMesh = null;
  31785. }
  31786. }
  31787. }
  31788. this._sortLODLevels();
  31789. return this;
  31790. };
  31791. /**
  31792. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31793. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31794. */
  31795. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31796. if (!this._LODLevels || this._LODLevels.length === 0) {
  31797. return this;
  31798. }
  31799. var bSphere;
  31800. if (boundingSphere) {
  31801. bSphere = boundingSphere;
  31802. }
  31803. else {
  31804. var boundingInfo = this.getBoundingInfo();
  31805. bSphere = boundingInfo.boundingSphere;
  31806. }
  31807. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31808. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31809. if (this.onLODLevelSelection) {
  31810. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31811. }
  31812. return this;
  31813. }
  31814. for (var index = 0; index < this._LODLevels.length; index++) {
  31815. var level = this._LODLevels[index];
  31816. if (level.distance < distanceToCamera) {
  31817. if (level.mesh) {
  31818. level.mesh._preActivate();
  31819. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31820. }
  31821. if (this.onLODLevelSelection) {
  31822. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31823. }
  31824. return level.mesh;
  31825. }
  31826. }
  31827. if (this.onLODLevelSelection) {
  31828. this.onLODLevelSelection(distanceToCamera, this, this);
  31829. }
  31830. return this;
  31831. };
  31832. Object.defineProperty(Mesh.prototype, "geometry", {
  31833. /**
  31834. * Returns the mesh internal Geometry object.
  31835. */
  31836. get: function () {
  31837. return this._geometry;
  31838. },
  31839. enumerable: true,
  31840. configurable: true
  31841. });
  31842. /**
  31843. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31844. */
  31845. Mesh.prototype.getTotalVertices = function () {
  31846. if (this._geometry === null || this._geometry === undefined) {
  31847. return 0;
  31848. }
  31849. return this._geometry.getTotalVertices();
  31850. };
  31851. /**
  31852. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31853. * 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.
  31854. * You can force the copy with forceCopy === true
  31855. * Returns null if the mesh has no geometry or no vertex buffer.
  31856. * Possible `kind` values :
  31857. * - BABYLON.VertexBuffer.PositionKind
  31858. * - BABYLON.VertexBuffer.UVKind
  31859. * - BABYLON.VertexBuffer.UV2Kind
  31860. * - BABYLON.VertexBuffer.UV3Kind
  31861. * - BABYLON.VertexBuffer.UV4Kind
  31862. * - BABYLON.VertexBuffer.UV5Kind
  31863. * - BABYLON.VertexBuffer.UV6Kind
  31864. * - BABYLON.VertexBuffer.ColorKind
  31865. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31866. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31867. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31868. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31869. */
  31870. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31871. if (!this._geometry) {
  31872. return null;
  31873. }
  31874. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31875. };
  31876. /**
  31877. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31878. * Returns `null` if the mesh has no geometry.
  31879. * Possible `kind` values :
  31880. * - BABYLON.VertexBuffer.PositionKind
  31881. * - BABYLON.VertexBuffer.UVKind
  31882. * - BABYLON.VertexBuffer.UV2Kind
  31883. * - BABYLON.VertexBuffer.UV3Kind
  31884. * - BABYLON.VertexBuffer.UV4Kind
  31885. * - BABYLON.VertexBuffer.UV5Kind
  31886. * - BABYLON.VertexBuffer.UV6Kind
  31887. * - BABYLON.VertexBuffer.ColorKind
  31888. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31889. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31890. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31891. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31892. */
  31893. Mesh.prototype.getVertexBuffer = function (kind) {
  31894. if (!this._geometry) {
  31895. return null;
  31896. }
  31897. return this._geometry.getVertexBuffer(kind);
  31898. };
  31899. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31900. if (!this._geometry) {
  31901. if (this._delayInfo) {
  31902. return this._delayInfo.indexOf(kind) !== -1;
  31903. }
  31904. return false;
  31905. }
  31906. return this._geometry.isVerticesDataPresent(kind);
  31907. };
  31908. /**
  31909. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31910. * Possible `kind` values :
  31911. * - BABYLON.VertexBuffer.PositionKind
  31912. * - BABYLON.VertexBuffer.UVKind
  31913. * - BABYLON.VertexBuffer.UV2Kind
  31914. * - BABYLON.VertexBuffer.UV3Kind
  31915. * - BABYLON.VertexBuffer.UV4Kind
  31916. * - BABYLON.VertexBuffer.UV5Kind
  31917. * - BABYLON.VertexBuffer.UV6Kind
  31918. * - BABYLON.VertexBuffer.ColorKind
  31919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31923. */
  31924. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31925. if (!this._geometry) {
  31926. if (this._delayInfo) {
  31927. return this._delayInfo.indexOf(kind) !== -1;
  31928. }
  31929. return false;
  31930. }
  31931. return this._geometry.isVertexBufferUpdatable(kind);
  31932. };
  31933. /**
  31934. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31935. * Possible `kind` values :
  31936. * - BABYLON.VertexBuffer.PositionKind
  31937. * - BABYLON.VertexBuffer.UVKind
  31938. * - BABYLON.VertexBuffer.UV2Kind
  31939. * - BABYLON.VertexBuffer.UV3Kind
  31940. * - BABYLON.VertexBuffer.UV4Kind
  31941. * - BABYLON.VertexBuffer.UV5Kind
  31942. * - BABYLON.VertexBuffer.UV6Kind
  31943. * - BABYLON.VertexBuffer.ColorKind
  31944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31948. */
  31949. Mesh.prototype.getVerticesDataKinds = function () {
  31950. if (!this._geometry) {
  31951. var result = new Array();
  31952. if (this._delayInfo) {
  31953. this._delayInfo.forEach(function (kind, index, array) {
  31954. result.push(kind);
  31955. });
  31956. }
  31957. return result;
  31958. }
  31959. return this._geometry.getVerticesDataKinds();
  31960. };
  31961. /**
  31962. * Returns a positive integer : the total number of indices in this mesh geometry.
  31963. * Returns zero if the mesh has no geometry.
  31964. */
  31965. Mesh.prototype.getTotalIndices = function () {
  31966. if (!this._geometry) {
  31967. return 0;
  31968. }
  31969. return this._geometry.getTotalIndices();
  31970. };
  31971. /**
  31972. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31973. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31974. * Returns an empty array if the mesh has no geometry.
  31975. */
  31976. Mesh.prototype.getIndices = function (copyWhenShared) {
  31977. if (!this._geometry) {
  31978. return [];
  31979. }
  31980. return this._geometry.getIndices(copyWhenShared);
  31981. };
  31982. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31983. get: function () {
  31984. return this._masterMesh !== null && this._masterMesh !== undefined;
  31985. },
  31986. enumerable: true,
  31987. configurable: true
  31988. });
  31989. /**
  31990. * Determine if the current mesh is ready to be rendered
  31991. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31992. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31993. * @returns true if all associated assets are ready (material, textures, shaders)
  31994. */
  31995. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31996. if (completeCheck === void 0) { completeCheck = false; }
  31997. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31998. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31999. return false;
  32000. }
  32001. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32002. return false;
  32003. }
  32004. if (!this.subMeshes || this.subMeshes.length === 0) {
  32005. return true;
  32006. }
  32007. if (!completeCheck) {
  32008. return true;
  32009. }
  32010. var engine = this.getEngine();
  32011. var scene = this.getScene();
  32012. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32013. this.computeWorldMatrix();
  32014. var mat = this.material || scene.defaultMaterial;
  32015. if (mat) {
  32016. if (mat.storeEffectOnSubMeshes) {
  32017. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32018. var subMesh = _a[_i];
  32019. var effectiveMaterial = subMesh.getMaterial();
  32020. if (effectiveMaterial) {
  32021. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32022. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32023. return false;
  32024. }
  32025. }
  32026. else {
  32027. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32028. return false;
  32029. }
  32030. }
  32031. }
  32032. }
  32033. }
  32034. else {
  32035. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32036. return false;
  32037. }
  32038. }
  32039. }
  32040. // Shadows
  32041. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32042. var light = _c[_b];
  32043. var generator = light.getShadowGenerator();
  32044. if (generator) {
  32045. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32046. var subMesh = _e[_d];
  32047. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32048. return false;
  32049. }
  32050. }
  32051. }
  32052. }
  32053. // LOD
  32054. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32055. var lod = _g[_f];
  32056. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32057. return false;
  32058. }
  32059. }
  32060. return true;
  32061. };
  32062. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32063. /**
  32064. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32065. * This property is pertinent only for updatable parametric shapes.
  32066. */
  32067. get: function () {
  32068. return this._areNormalsFrozen;
  32069. },
  32070. enumerable: true,
  32071. configurable: true
  32072. });
  32073. /**
  32074. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32075. * It has no effect at all on other shapes.
  32076. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32077. * Returns the Mesh.
  32078. */
  32079. Mesh.prototype.freezeNormals = function () {
  32080. this._areNormalsFrozen = true;
  32081. return this;
  32082. };
  32083. /**
  32084. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32085. * It has no effect at all on other shapes.
  32086. * It reactivates the mesh normals computation if it was previously frozen.
  32087. * Returns the Mesh.
  32088. */
  32089. Mesh.prototype.unfreezeNormals = function () {
  32090. this._areNormalsFrozen = false;
  32091. return this;
  32092. };
  32093. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32094. /**
  32095. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32096. */
  32097. set: function (count) {
  32098. this._overridenInstanceCount = count;
  32099. },
  32100. enumerable: true,
  32101. configurable: true
  32102. });
  32103. // Methods
  32104. Mesh.prototype._preActivate = function () {
  32105. var sceneRenderId = this.getScene().getRenderId();
  32106. if (this._preActivateId === sceneRenderId) {
  32107. return this;
  32108. }
  32109. this._preActivateId = sceneRenderId;
  32110. this._visibleInstances = null;
  32111. return this;
  32112. };
  32113. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32114. if (this._visibleInstances) {
  32115. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32116. }
  32117. return this;
  32118. };
  32119. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32120. if (!this._visibleInstances) {
  32121. this._visibleInstances = {};
  32122. this._visibleInstances.defaultRenderId = renderId;
  32123. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32124. }
  32125. if (!this._visibleInstances[renderId]) {
  32126. this._visibleInstances[renderId] = new Array();
  32127. }
  32128. this._visibleInstances[renderId].push(instance);
  32129. return this;
  32130. };
  32131. /**
  32132. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32133. * This means the mesh underlying bounding box and sphere are recomputed.
  32134. * Returns the Mesh.
  32135. */
  32136. Mesh.prototype.refreshBoundingInfo = function () {
  32137. return this._refreshBoundingInfo(false);
  32138. };
  32139. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32140. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32141. return this;
  32142. }
  32143. var data = this._getPositionData(applySkeleton);
  32144. if (data) {
  32145. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32146. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32147. }
  32148. if (this.subMeshes) {
  32149. for (var index = 0; index < this.subMeshes.length; index++) {
  32150. this.subMeshes[index].refreshBoundingInfo();
  32151. }
  32152. }
  32153. this._updateBoundingInfo();
  32154. return this;
  32155. };
  32156. Mesh.prototype._getPositionData = function (applySkeleton) {
  32157. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32158. if (data && applySkeleton && this.skeleton) {
  32159. data = BABYLON.Tools.Slice(data);
  32160. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32161. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32162. if (matricesWeightsData && matricesIndicesData) {
  32163. var needExtras = this.numBoneInfluencers > 4;
  32164. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32165. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32166. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32167. var tempVector = BABYLON.Tmp.Vector3[0];
  32168. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32169. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32170. var matWeightIdx = 0;
  32171. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32172. finalMatrix.reset();
  32173. var inf;
  32174. var weight;
  32175. for (inf = 0; inf < 4; inf++) {
  32176. weight = matricesWeightsData[matWeightIdx + inf];
  32177. if (weight <= 0)
  32178. break;
  32179. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32180. finalMatrix.addToSelf(tempMatrix);
  32181. }
  32182. if (needExtras) {
  32183. for (inf = 0; inf < 4; inf++) {
  32184. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32185. if (weight <= 0)
  32186. break;
  32187. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32188. finalMatrix.addToSelf(tempMatrix);
  32189. }
  32190. }
  32191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32192. tempVector.toArray(data, index);
  32193. }
  32194. }
  32195. }
  32196. return data;
  32197. };
  32198. Mesh.prototype._createGlobalSubMesh = function (force) {
  32199. var totalVertices = this.getTotalVertices();
  32200. if (!totalVertices || !this.getIndices()) {
  32201. return null;
  32202. }
  32203. // Check if we need to recreate the submeshes
  32204. if (this.subMeshes && this.subMeshes.length > 0) {
  32205. var ib = this.getIndices();
  32206. if (!ib) {
  32207. return null;
  32208. }
  32209. var totalIndices = ib.length;
  32210. var needToRecreate = false;
  32211. if (force) {
  32212. needToRecreate = true;
  32213. }
  32214. else {
  32215. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32216. var submesh = _a[_i];
  32217. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32218. needToRecreate = true;
  32219. break;
  32220. }
  32221. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32222. needToRecreate = true;
  32223. break;
  32224. }
  32225. }
  32226. }
  32227. if (!needToRecreate) {
  32228. return this.subMeshes[0];
  32229. }
  32230. }
  32231. this.releaseSubMeshes();
  32232. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32233. };
  32234. Mesh.prototype.subdivide = function (count) {
  32235. if (count < 1) {
  32236. return;
  32237. }
  32238. var totalIndices = this.getTotalIndices();
  32239. var subdivisionSize = (totalIndices / count) | 0;
  32240. var offset = 0;
  32241. // Ensure that subdivisionSize is a multiple of 3
  32242. while (subdivisionSize % 3 !== 0) {
  32243. subdivisionSize++;
  32244. }
  32245. this.releaseSubMeshes();
  32246. for (var index = 0; index < count; index++) {
  32247. if (offset >= totalIndices) {
  32248. break;
  32249. }
  32250. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32251. offset += subdivisionSize;
  32252. }
  32253. this.synchronizeInstances();
  32254. };
  32255. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32256. if (updatable === void 0) { updatable = false; }
  32257. if (!this._geometry) {
  32258. var vertexData = new BABYLON.VertexData();
  32259. vertexData.set(data, kind);
  32260. var scene = this.getScene();
  32261. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32262. }
  32263. else {
  32264. this._geometry.setVerticesData(kind, data, updatable, stride);
  32265. }
  32266. return this;
  32267. };
  32268. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32269. if (updatable === void 0) { updatable = true; }
  32270. var vb = this.getVertexBuffer(kind);
  32271. if (!vb || vb.isUpdatable() === updatable) {
  32272. return;
  32273. }
  32274. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32275. };
  32276. /**
  32277. * Sets the mesh VertexBuffer.
  32278. * Returns the Mesh.
  32279. */
  32280. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32281. if (!this._geometry) {
  32282. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32283. }
  32284. this._geometry.setVerticesBuffer(buffer);
  32285. return this;
  32286. };
  32287. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32288. if (!this._geometry) {
  32289. return this;
  32290. }
  32291. if (!makeItUnique) {
  32292. this._geometry.updateVerticesData(kind, data, updateExtends);
  32293. }
  32294. else {
  32295. this.makeGeometryUnique();
  32296. this.updateVerticesData(kind, data, updateExtends, false);
  32297. }
  32298. return this;
  32299. };
  32300. /**
  32301. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32302. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32303. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32304. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32305. * Returns the Mesh.
  32306. */
  32307. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32308. if (computeNormals === void 0) { computeNormals = true; }
  32309. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32310. if (!positions) {
  32311. return this;
  32312. }
  32313. positionFunction(positions);
  32314. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32315. if (computeNormals) {
  32316. var indices = this.getIndices();
  32317. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32318. if (!normals) {
  32319. return this;
  32320. }
  32321. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32322. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32323. }
  32324. return this;
  32325. };
  32326. /**
  32327. * Creates a un-shared specific occurence of the geometry for the mesh.
  32328. * Returns the Mesh.
  32329. */
  32330. Mesh.prototype.makeGeometryUnique = function () {
  32331. if (!this._geometry) {
  32332. return this;
  32333. }
  32334. var oldGeometry = this._geometry;
  32335. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32336. oldGeometry.releaseForMesh(this, true);
  32337. geometry.applyToMesh(this);
  32338. return this;
  32339. };
  32340. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32341. if (totalVertices === void 0) { totalVertices = null; }
  32342. if (updatable === void 0) { updatable = false; }
  32343. if (!this._geometry) {
  32344. var vertexData = new BABYLON.VertexData();
  32345. vertexData.indices = indices;
  32346. var scene = this.getScene();
  32347. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32348. }
  32349. else {
  32350. this._geometry.setIndices(indices, totalVertices, updatable);
  32351. }
  32352. return this;
  32353. };
  32354. /**
  32355. * Update the current index buffer
  32356. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32357. * Returns the Mesh.
  32358. */
  32359. Mesh.prototype.updateIndices = function (indices, offset) {
  32360. if (!this._geometry) {
  32361. return this;
  32362. }
  32363. this._geometry.updateIndices(indices, offset);
  32364. return this;
  32365. };
  32366. /**
  32367. * Invert the geometry to move from a right handed system to a left handed one.
  32368. * Returns the Mesh.
  32369. */
  32370. Mesh.prototype.toLeftHanded = function () {
  32371. if (!this._geometry) {
  32372. return this;
  32373. }
  32374. this._geometry.toLeftHanded();
  32375. return this;
  32376. };
  32377. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32378. if (!this._geometry) {
  32379. return this;
  32380. }
  32381. var engine = this.getScene().getEngine();
  32382. // Wireframe
  32383. var indexToBind;
  32384. if (this._unIndexed) {
  32385. indexToBind = null;
  32386. }
  32387. else {
  32388. switch (fillMode) {
  32389. case BABYLON.Material.PointFillMode:
  32390. indexToBind = null;
  32391. break;
  32392. case BABYLON.Material.WireFrameFillMode:
  32393. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32394. break;
  32395. default:
  32396. case BABYLON.Material.TriangleFillMode:
  32397. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32398. break;
  32399. }
  32400. }
  32401. // VBOs
  32402. this._geometry._bind(effect, indexToBind);
  32403. return this;
  32404. };
  32405. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32406. if (alternate === void 0) { alternate = false; }
  32407. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32408. return this;
  32409. }
  32410. this.onBeforeDrawObservable.notifyObservers(this);
  32411. var scene = this.getScene();
  32412. var engine = scene.getEngine();
  32413. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32414. // or triangles as points
  32415. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32416. }
  32417. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32418. // Triangles as wireframe
  32419. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32420. }
  32421. else {
  32422. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32423. }
  32424. if (scene._isAlternateRenderingEnabled && !alternate) {
  32425. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32426. if (!effect || !scene.activeCamera) {
  32427. return this;
  32428. }
  32429. scene._switchToAlternateCameraConfiguration(true);
  32430. this._effectiveMaterial.bindView(effect);
  32431. this._effectiveMaterial.bindViewProjection(effect);
  32432. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32433. this._draw(subMesh, fillMode, instancesCount, true);
  32434. engine.setViewport(scene.activeCamera.viewport);
  32435. scene._switchToAlternateCameraConfiguration(false);
  32436. this._effectiveMaterial.bindView(effect);
  32437. this._effectiveMaterial.bindViewProjection(effect);
  32438. }
  32439. return this;
  32440. };
  32441. /**
  32442. * Registers for this mesh a javascript function called just before the rendering process.
  32443. * This function is passed the current mesh.
  32444. * Return the Mesh.
  32445. */
  32446. Mesh.prototype.registerBeforeRender = function (func) {
  32447. this.onBeforeRenderObservable.add(func);
  32448. return this;
  32449. };
  32450. /**
  32451. * Disposes a previously registered javascript function called before the rendering.
  32452. * This function is passed the current mesh.
  32453. * Returns the Mesh.
  32454. */
  32455. Mesh.prototype.unregisterBeforeRender = function (func) {
  32456. this.onBeforeRenderObservable.removeCallback(func);
  32457. return this;
  32458. };
  32459. /**
  32460. * Registers for this mesh a javascript function called just after the rendering is complete.
  32461. * This function is passed the current mesh.
  32462. * Returns the Mesh.
  32463. */
  32464. Mesh.prototype.registerAfterRender = function (func) {
  32465. this.onAfterRenderObservable.add(func);
  32466. return this;
  32467. };
  32468. /**
  32469. * Disposes a previously registered javascript function called after the rendering.
  32470. * This function is passed the current mesh.
  32471. * Return the Mesh.
  32472. */
  32473. Mesh.prototype.unregisterAfterRender = function (func) {
  32474. this.onAfterRenderObservable.removeCallback(func);
  32475. return this;
  32476. };
  32477. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32478. var scene = this.getScene();
  32479. this._batchCache.mustReturn = false;
  32480. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32481. this._batchCache.visibleInstances[subMeshId] = null;
  32482. if (this._visibleInstances) {
  32483. var currentRenderId = scene.getRenderId();
  32484. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32485. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32486. var selfRenderId = this._renderId;
  32487. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32488. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32489. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32490. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32491. }
  32492. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32493. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32494. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32495. this._batchCache.mustReturn = true;
  32496. return this._batchCache;
  32497. }
  32498. if (currentRenderId !== selfRenderId) {
  32499. this._batchCache.renderSelf[subMeshId] = false;
  32500. }
  32501. }
  32502. this._renderIdForInstances[subMeshId] = currentRenderId;
  32503. }
  32504. return this._batchCache;
  32505. };
  32506. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32507. var visibleInstances = batch.visibleInstances[subMesh._id];
  32508. if (!visibleInstances) {
  32509. return this;
  32510. }
  32511. var matricesCount = visibleInstances.length + 1;
  32512. var bufferSize = matricesCount * 16 * 4;
  32513. var currentInstancesBufferSize = this._instancesBufferSize;
  32514. var instancesBuffer = this._instancesBuffer;
  32515. while (this._instancesBufferSize < bufferSize) {
  32516. this._instancesBufferSize *= 2;
  32517. }
  32518. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32519. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32520. }
  32521. var offset = 0;
  32522. var instancesCount = 0;
  32523. var world = this.getWorldMatrix();
  32524. if (batch.renderSelf[subMesh._id]) {
  32525. world.copyToArray(this._instancesData, offset);
  32526. offset += 16;
  32527. instancesCount++;
  32528. }
  32529. if (visibleInstances) {
  32530. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32531. var instance = visibleInstances[instanceIndex];
  32532. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32533. offset += 16;
  32534. instancesCount++;
  32535. }
  32536. }
  32537. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32538. if (instancesBuffer) {
  32539. instancesBuffer.dispose();
  32540. }
  32541. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32542. this._instancesBuffer = instancesBuffer;
  32543. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32544. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32545. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32546. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32547. }
  32548. else {
  32549. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32550. }
  32551. this._bind(subMesh, effect, fillMode);
  32552. this._draw(subMesh, fillMode, instancesCount);
  32553. engine.unbindInstanceAttributes();
  32554. return this;
  32555. };
  32556. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32557. var scene = this.getScene();
  32558. var engine = scene.getEngine();
  32559. if (hardwareInstancedRendering) {
  32560. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32561. }
  32562. else {
  32563. if (batch.renderSelf[subMesh._id]) {
  32564. // Draw
  32565. if (onBeforeDraw) {
  32566. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32567. }
  32568. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32569. }
  32570. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32571. if (visibleInstancesForSubMesh) {
  32572. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32573. var instance = visibleInstancesForSubMesh[instanceIndex];
  32574. // World
  32575. var world = instance.getWorldMatrix();
  32576. if (onBeforeDraw) {
  32577. onBeforeDraw(true, world, effectiveMaterial);
  32578. }
  32579. // Draw
  32580. this._draw(subMesh, fillMode);
  32581. }
  32582. }
  32583. }
  32584. return this;
  32585. };
  32586. /**
  32587. * Triggers the draw call for the mesh.
  32588. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32589. * Returns the Mesh.
  32590. */
  32591. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32592. this._checkOcclusionQuery();
  32593. if (this._isOccluded) {
  32594. return this;
  32595. }
  32596. var scene = this.getScene();
  32597. // Managing instances
  32598. var batch = this._getInstancesRenderList(subMesh._id);
  32599. if (batch.mustReturn) {
  32600. return this;
  32601. }
  32602. // Checking geometry state
  32603. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32604. return this;
  32605. }
  32606. this.onBeforeRenderObservable.notifyObservers(this);
  32607. var engine = scene.getEngine();
  32608. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32609. // Material
  32610. var material = subMesh.getMaterial();
  32611. if (!material) {
  32612. return this;
  32613. }
  32614. this._effectiveMaterial = material;
  32615. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32616. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32617. return this;
  32618. }
  32619. }
  32620. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32621. return this;
  32622. }
  32623. // Alpha mode
  32624. if (enableAlphaMode) {
  32625. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32626. }
  32627. // Outline - step 1
  32628. var savedDepthWrite = engine.getDepthWrite();
  32629. if (this.renderOutline) {
  32630. engine.setDepthWrite(false);
  32631. scene.getOutlineRenderer().render(subMesh, batch);
  32632. engine.setDepthWrite(savedDepthWrite);
  32633. }
  32634. var effect;
  32635. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32636. effect = subMesh.effect;
  32637. }
  32638. else {
  32639. effect = this._effectiveMaterial.getEffect();
  32640. }
  32641. if (!effect) {
  32642. return this;
  32643. }
  32644. var sideOrientation = this.overrideMaterialSideOrientation;
  32645. if (sideOrientation == null) {
  32646. sideOrientation = this._effectiveMaterial.sideOrientation;
  32647. if (this._getWorldMatrixDeterminant() < 0) {
  32648. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32649. }
  32650. }
  32651. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32652. if (this._effectiveMaterial.forceDepthWrite) {
  32653. engine.setDepthWrite(true);
  32654. }
  32655. // Bind
  32656. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32657. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32658. this._bind(subMesh, effect, fillMode);
  32659. }
  32660. var world = this.getWorldMatrix();
  32661. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32662. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32663. }
  32664. else {
  32665. this._effectiveMaterial.bind(world, this);
  32666. }
  32667. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32668. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32669. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32670. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32671. }
  32672. // Draw
  32673. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32674. // Unbind
  32675. this._effectiveMaterial.unbind();
  32676. // Outline - step 2
  32677. if (this.renderOutline && savedDepthWrite) {
  32678. engine.setDepthWrite(true);
  32679. engine.setColorWrite(false);
  32680. scene.getOutlineRenderer().render(subMesh, batch);
  32681. engine.setColorWrite(true);
  32682. }
  32683. // Overlay
  32684. if (this.renderOverlay) {
  32685. var currentMode = engine.getAlphaMode();
  32686. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32687. scene.getOutlineRenderer().render(subMesh, batch, true);
  32688. engine.setAlphaMode(currentMode);
  32689. }
  32690. this.onAfterRenderObservable.notifyObservers(this);
  32691. return this;
  32692. };
  32693. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32694. if (isInstance && effectiveMaterial) {
  32695. effectiveMaterial.bindOnlyWorldMatrix(world);
  32696. }
  32697. };
  32698. /**
  32699. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32700. */
  32701. Mesh.prototype.getEmittedParticleSystems = function () {
  32702. var results = new Array();
  32703. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32704. var particleSystem = this.getScene().particleSystems[index];
  32705. if (particleSystem.emitter === this) {
  32706. results.push(particleSystem);
  32707. }
  32708. }
  32709. return results;
  32710. };
  32711. /**
  32712. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32713. */
  32714. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32715. var results = new Array();
  32716. var descendants = this.getDescendants();
  32717. descendants.push(this);
  32718. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32719. var particleSystem = this.getScene().particleSystems[index];
  32720. var emitter = particleSystem.emitter;
  32721. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32722. results.push(particleSystem);
  32723. }
  32724. }
  32725. return results;
  32726. };
  32727. /**
  32728. * Normalize matrix weights so that all vertices have a total weight set to 1
  32729. */
  32730. Mesh.prototype.cleanMatrixWeights = function () {
  32731. var epsilon = 1e-3;
  32732. var noInfluenceBoneIndex = 0.0;
  32733. if (this.skeleton) {
  32734. noInfluenceBoneIndex = this.skeleton.bones.length;
  32735. }
  32736. else {
  32737. return;
  32738. }
  32739. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32740. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32741. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32742. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32743. var influencers = this.numBoneInfluencers;
  32744. var size = matricesWeights.length;
  32745. for (var i = 0; i < size; i += 4) {
  32746. var weight = 0.0;
  32747. var firstZeroWeight = -1;
  32748. for (var j = 0; j < 4; j++) {
  32749. var w = matricesWeights[i + j];
  32750. weight += w;
  32751. if (w < epsilon && firstZeroWeight < 0) {
  32752. firstZeroWeight = j;
  32753. }
  32754. }
  32755. if (matricesWeightsExtra) {
  32756. for (var j = 0; j < 4; j++) {
  32757. var w = matricesWeightsExtra[i + j];
  32758. weight += w;
  32759. if (w < epsilon && firstZeroWeight < 0) {
  32760. firstZeroWeight = j + 4;
  32761. }
  32762. }
  32763. }
  32764. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32765. firstZeroWeight = influencers - 1;
  32766. }
  32767. if (weight > epsilon) {
  32768. var mweight = 1.0 / weight;
  32769. for (var j = 0; j < 4; j++) {
  32770. matricesWeights[i + j] *= mweight;
  32771. }
  32772. if (matricesWeightsExtra) {
  32773. for (var j = 0; j < 4; j++) {
  32774. matricesWeightsExtra[i + j] *= mweight;
  32775. }
  32776. }
  32777. }
  32778. else {
  32779. if (firstZeroWeight >= 4) {
  32780. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32781. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32782. }
  32783. else {
  32784. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32785. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32786. }
  32787. }
  32788. }
  32789. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32790. if (matricesIndicesExtra) {
  32791. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32792. }
  32793. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32794. if (matricesWeightsExtra) {
  32795. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32796. }
  32797. };
  32798. Mesh.prototype._checkDelayState = function () {
  32799. var scene = this.getScene();
  32800. if (this._geometry) {
  32801. this._geometry.load(scene);
  32802. }
  32803. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32804. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32805. this._queueLoad(scene);
  32806. }
  32807. return this;
  32808. };
  32809. Mesh.prototype._queueLoad = function (scene) {
  32810. var _this = this;
  32811. scene._addPendingData(this);
  32812. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32813. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32814. if (data instanceof ArrayBuffer) {
  32815. _this._delayLoadingFunction(data, _this);
  32816. }
  32817. else {
  32818. _this._delayLoadingFunction(JSON.parse(data), _this);
  32819. }
  32820. _this.instances.forEach(function (instance) {
  32821. instance._syncSubMeshes();
  32822. });
  32823. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32824. scene._removePendingData(_this);
  32825. }, function () { }, scene.database, getBinaryData);
  32826. return this;
  32827. };
  32828. /**
  32829. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32830. */
  32831. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32832. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32833. return false;
  32834. }
  32835. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32836. return false;
  32837. }
  32838. this._checkDelayState();
  32839. return true;
  32840. };
  32841. /**
  32842. * Sets the mesh material by the material or multiMaterial `id` property.
  32843. * The material `id` is a string identifying the material or the multiMaterial.
  32844. * This method returns the Mesh.
  32845. */
  32846. Mesh.prototype.setMaterialByID = function (id) {
  32847. var materials = this.getScene().materials;
  32848. var index;
  32849. for (index = materials.length - 1; index > -1; index--) {
  32850. if (materials[index].id === id) {
  32851. this.material = materials[index];
  32852. return this;
  32853. }
  32854. }
  32855. // Multi
  32856. var multiMaterials = this.getScene().multiMaterials;
  32857. for (index = multiMaterials.length - 1; index > -1; index--) {
  32858. if (multiMaterials[index].id === id) {
  32859. this.material = multiMaterials[index];
  32860. return this;
  32861. }
  32862. }
  32863. return this;
  32864. };
  32865. /**
  32866. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32867. */
  32868. Mesh.prototype.getAnimatables = function () {
  32869. var results = new Array();
  32870. if (this.material) {
  32871. results.push(this.material);
  32872. }
  32873. if (this.skeleton) {
  32874. results.push(this.skeleton);
  32875. }
  32876. return results;
  32877. };
  32878. /**
  32879. * Modifies the mesh geometry according to the passed transformation matrix.
  32880. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32881. * The mesh normals are modified accordingly the same transformation.
  32882. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32883. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32884. * Returns the Mesh.
  32885. */
  32886. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32887. // Position
  32888. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32889. return this;
  32890. }
  32891. var submeshes = this.subMeshes.splice(0);
  32892. this._resetPointsArrayCache();
  32893. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32894. var temp = new Array();
  32895. var index;
  32896. for (index = 0; index < data.length; index += 3) {
  32897. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32898. }
  32899. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32900. // Normals
  32901. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32902. return this;
  32903. }
  32904. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32905. temp = [];
  32906. for (index = 0; index < data.length; index += 3) {
  32907. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32908. }
  32909. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32910. // flip faces?
  32911. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32912. this.flipFaces();
  32913. }
  32914. // Restore submeshes
  32915. this.releaseSubMeshes();
  32916. this.subMeshes = submeshes;
  32917. return this;
  32918. };
  32919. /**
  32920. * Modifies the mesh geometry according to its own current World Matrix.
  32921. * The mesh World Matrix is then reset.
  32922. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32923. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32924. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32925. * Returns the Mesh.
  32926. */
  32927. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32928. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32929. this.scaling.copyFromFloats(1, 1, 1);
  32930. this.position.copyFromFloats(0, 0, 0);
  32931. this.rotation.copyFromFloats(0, 0, 0);
  32932. //only if quaternion is already set
  32933. if (this.rotationQuaternion) {
  32934. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32935. }
  32936. this._worldMatrix = BABYLON.Matrix.Identity();
  32937. return this;
  32938. };
  32939. Object.defineProperty(Mesh.prototype, "_positions", {
  32940. // Cache
  32941. get: function () {
  32942. if (this._geometry) {
  32943. return this._geometry._positions;
  32944. }
  32945. return null;
  32946. },
  32947. enumerable: true,
  32948. configurable: true
  32949. });
  32950. Mesh.prototype._resetPointsArrayCache = function () {
  32951. if (this._geometry) {
  32952. this._geometry._resetPointsArrayCache();
  32953. }
  32954. return this;
  32955. };
  32956. Mesh.prototype._generatePointsArray = function () {
  32957. if (this._geometry) {
  32958. return this._geometry._generatePointsArray();
  32959. }
  32960. return false;
  32961. };
  32962. /**
  32963. * Returns a new Mesh object generated from the current mesh properties.
  32964. * This method must not get confused with createInstance().
  32965. * The parameter `name` is a string, the name given to the new mesh.
  32966. * The optional parameter `newParent` can be any Node object (default `null`).
  32967. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32968. * 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.
  32969. */
  32970. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32971. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32972. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32973. };
  32974. /**
  32975. * Releases resources associated with this mesh.
  32976. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32977. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32978. */
  32979. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32980. var _this = this;
  32981. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32982. this.morphTargetManager = null;
  32983. if (this._geometry) {
  32984. this._geometry.releaseForMesh(this, true);
  32985. }
  32986. // Sources
  32987. var meshes = this.getScene().meshes;
  32988. meshes.forEach(function (abstractMesh) {
  32989. var mesh = abstractMesh;
  32990. if (mesh._source && mesh._source === _this) {
  32991. mesh._source = null;
  32992. }
  32993. });
  32994. this._source = null;
  32995. // Instances
  32996. if (this._instancesBuffer) {
  32997. this._instancesBuffer.dispose();
  32998. this._instancesBuffer = null;
  32999. }
  33000. while (this.instances.length) {
  33001. this.instances[0].dispose();
  33002. }
  33003. // Effect layers.
  33004. var effectLayers = this.getScene().effectLayers;
  33005. for (var i = 0; i < effectLayers.length; i++) {
  33006. var effectLayer = effectLayers[i];
  33007. if (effectLayer) {
  33008. effectLayer._disposeMesh(this);
  33009. }
  33010. }
  33011. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33012. };
  33013. /**
  33014. * Modifies the mesh geometry according to a displacement map.
  33015. * 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.
  33016. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33017. * This method returns nothing.
  33018. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33019. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33020. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33021. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33022. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33023. *
  33024. * Returns the Mesh.
  33025. */
  33026. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33027. var _this = this;
  33028. var scene = this.getScene();
  33029. var onload = function (img) {
  33030. // Getting height map data
  33031. var canvas = document.createElement("canvas");
  33032. var context = canvas.getContext("2d");
  33033. var heightMapWidth = img.width;
  33034. var heightMapHeight = img.height;
  33035. canvas.width = heightMapWidth;
  33036. canvas.height = heightMapHeight;
  33037. context.drawImage(img, 0, 0);
  33038. // Create VertexData from map data
  33039. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33040. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33041. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33042. //execute success callback, if set
  33043. if (onSuccess) {
  33044. onSuccess(_this);
  33045. }
  33046. };
  33047. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33048. return this;
  33049. };
  33050. /**
  33051. * Modifies the mesh geometry according to a displacementMap buffer.
  33052. * 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.
  33053. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33054. * This method returns nothing.
  33055. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33056. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33057. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33058. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33059. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33060. *
  33061. * Returns the Mesh.
  33062. */
  33063. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33064. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33065. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33066. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33067. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33068. return this;
  33069. }
  33070. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33071. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33072. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33073. var position = BABYLON.Vector3.Zero();
  33074. var normal = BABYLON.Vector3.Zero();
  33075. var uv = BABYLON.Vector2.Zero();
  33076. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33077. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33078. for (var index = 0; index < positions.length; index += 3) {
  33079. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33080. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33081. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33082. // Compute height
  33083. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33084. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33085. var pos = (u + v * heightMapWidth) * 4;
  33086. var r = buffer[pos] / 255.0;
  33087. var g = buffer[pos + 1] / 255.0;
  33088. var b = buffer[pos + 2] / 255.0;
  33089. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33090. normal.normalize();
  33091. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33092. position = position.add(normal);
  33093. position.toArray(positions, index);
  33094. }
  33095. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33096. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33097. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33098. return this;
  33099. };
  33100. /**
  33101. * Modify the mesh to get a flat shading rendering.
  33102. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33103. * This method returns the Mesh.
  33104. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33105. */
  33106. Mesh.prototype.convertToFlatShadedMesh = function () {
  33107. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33108. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33109. var kinds = this.getVerticesDataKinds();
  33110. var vbs = {};
  33111. var data = {};
  33112. var newdata = {};
  33113. var updatableNormals = false;
  33114. var kindIndex;
  33115. var kind;
  33116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33117. kind = kinds[kindIndex];
  33118. var vertexBuffer = this.getVertexBuffer(kind);
  33119. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33120. updatableNormals = vertexBuffer.isUpdatable();
  33121. kinds.splice(kindIndex, 1);
  33122. kindIndex--;
  33123. continue;
  33124. }
  33125. vbs[kind] = vertexBuffer;
  33126. data[kind] = vbs[kind].getData();
  33127. newdata[kind] = [];
  33128. }
  33129. // Save previous submeshes
  33130. var previousSubmeshes = this.subMeshes.slice(0);
  33131. var indices = this.getIndices();
  33132. var totalIndices = this.getTotalIndices();
  33133. // Generating unique vertices per face
  33134. var index;
  33135. for (index = 0; index < totalIndices; index++) {
  33136. var vertexIndex = indices[index];
  33137. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33138. kind = kinds[kindIndex];
  33139. var stride = vbs[kind].getStrideSize();
  33140. for (var offset = 0; offset < stride; offset++) {
  33141. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33142. }
  33143. }
  33144. }
  33145. // Updating faces & normal
  33146. var normals = [];
  33147. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33148. for (index = 0; index < totalIndices; index += 3) {
  33149. indices[index] = index;
  33150. indices[index + 1] = index + 1;
  33151. indices[index + 2] = index + 2;
  33152. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33153. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33154. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33155. var p1p2 = p1.subtract(p2);
  33156. var p3p2 = p3.subtract(p2);
  33157. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33158. // Store same normals for every vertex
  33159. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33160. normals.push(normal.x);
  33161. normals.push(normal.y);
  33162. normals.push(normal.z);
  33163. }
  33164. }
  33165. this.setIndices(indices);
  33166. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33167. // Updating vertex buffers
  33168. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33169. kind = kinds[kindIndex];
  33170. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33171. }
  33172. // Updating submeshes
  33173. this.releaseSubMeshes();
  33174. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33175. var previousOne = previousSubmeshes[submeshIndex];
  33176. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33177. }
  33178. this.synchronizeInstances();
  33179. return this;
  33180. };
  33181. /**
  33182. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33183. * In other words, more vertices, no more indices and a single bigger VBO.
  33184. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33185. * Returns the Mesh.
  33186. */
  33187. Mesh.prototype.convertToUnIndexedMesh = function () {
  33188. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33189. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33190. var kinds = this.getVerticesDataKinds();
  33191. var vbs = {};
  33192. var data = {};
  33193. var newdata = {};
  33194. var kindIndex;
  33195. var kind;
  33196. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33197. kind = kinds[kindIndex];
  33198. var vertexBuffer = this.getVertexBuffer(kind);
  33199. vbs[kind] = vertexBuffer;
  33200. data[kind] = vbs[kind].getData();
  33201. newdata[kind] = [];
  33202. }
  33203. // Save previous submeshes
  33204. var previousSubmeshes = this.subMeshes.slice(0);
  33205. var indices = this.getIndices();
  33206. var totalIndices = this.getTotalIndices();
  33207. // Generating unique vertices per face
  33208. var index;
  33209. for (index = 0; index < totalIndices; index++) {
  33210. var vertexIndex = indices[index];
  33211. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33212. kind = kinds[kindIndex];
  33213. var stride = vbs[kind].getStrideSize();
  33214. for (var offset = 0; offset < stride; offset++) {
  33215. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33216. }
  33217. }
  33218. }
  33219. // Updating indices
  33220. for (index = 0; index < totalIndices; index += 3) {
  33221. indices[index] = index;
  33222. indices[index + 1] = index + 1;
  33223. indices[index + 2] = index + 2;
  33224. }
  33225. this.setIndices(indices);
  33226. // Updating vertex buffers
  33227. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33228. kind = kinds[kindIndex];
  33229. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33230. }
  33231. // Updating submeshes
  33232. this.releaseSubMeshes();
  33233. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33234. var previousOne = previousSubmeshes[submeshIndex];
  33235. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33236. }
  33237. this._unIndexed = true;
  33238. this.synchronizeInstances();
  33239. return this;
  33240. };
  33241. /**
  33242. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33243. * This method returns the Mesh.
  33244. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33245. */
  33246. Mesh.prototype.flipFaces = function (flipNormals) {
  33247. if (flipNormals === void 0) { flipNormals = false; }
  33248. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33249. var i;
  33250. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33251. for (i = 0; i < vertex_data.normals.length; i++) {
  33252. vertex_data.normals[i] *= -1;
  33253. }
  33254. }
  33255. if (vertex_data.indices) {
  33256. var temp;
  33257. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33258. // reassign indices
  33259. temp = vertex_data.indices[i + 1];
  33260. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33261. vertex_data.indices[i + 2] = temp;
  33262. }
  33263. }
  33264. vertex_data.applyToMesh(this);
  33265. return this;
  33266. };
  33267. // Instances
  33268. /**
  33269. * Creates a new InstancedMesh object from the mesh model.
  33270. * An instance shares the same properties and the same material than its model.
  33271. * Only these properties of each instance can then be set individually :
  33272. * - position
  33273. * - rotation
  33274. * - rotationQuaternion
  33275. * - setPivotMatrix
  33276. * - scaling
  33277. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33278. * Warning : this method is not supported for Line mesh and LineSystem
  33279. */
  33280. Mesh.prototype.createInstance = function (name) {
  33281. return new BABYLON.InstancedMesh(name, this);
  33282. };
  33283. /**
  33284. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33285. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33286. * This method returns the Mesh.
  33287. */
  33288. Mesh.prototype.synchronizeInstances = function () {
  33289. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33290. var instance = this.instances[instanceIndex];
  33291. instance._syncSubMeshes();
  33292. }
  33293. return this;
  33294. };
  33295. /**
  33296. * Simplify the mesh according to the given array of settings.
  33297. * Function will return immediately and will simplify async. It returns the Mesh.
  33298. * @param settings a collection of simplification settings.
  33299. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33300. * @param type the type of simplification to run.
  33301. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33302. */
  33303. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33304. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33305. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33306. this.getScene().simplificationQueue.addTask({
  33307. settings: settings,
  33308. parallelProcessing: parallelProcessing,
  33309. mesh: this,
  33310. simplificationType: simplificationType,
  33311. successCallback: successCallback
  33312. });
  33313. return this;
  33314. };
  33315. /**
  33316. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33317. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33318. * This should be used together with the simplification to avoid disappearing triangles.
  33319. * Returns the Mesh.
  33320. * @param successCallback an optional success callback to be called after the optimization finished.
  33321. */
  33322. Mesh.prototype.optimizeIndices = function (successCallback) {
  33323. var _this = this;
  33324. var indices = this.getIndices();
  33325. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33326. if (!positions || !indices) {
  33327. return this;
  33328. }
  33329. var vectorPositions = new Array();
  33330. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33331. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33332. }
  33333. var dupes = new Array();
  33334. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33335. var realPos = vectorPositions.length - 1 - iteration;
  33336. var testedPosition = vectorPositions[realPos];
  33337. for (var j = 0; j < realPos; ++j) {
  33338. var againstPosition = vectorPositions[j];
  33339. if (testedPosition.equals(againstPosition)) {
  33340. dupes[realPos] = j;
  33341. break;
  33342. }
  33343. }
  33344. }, function () {
  33345. for (var i = 0; i < indices.length; ++i) {
  33346. indices[i] = dupes[indices[i]] || indices[i];
  33347. }
  33348. //indices are now reordered
  33349. var originalSubMeshes = _this.subMeshes.slice(0);
  33350. _this.setIndices(indices);
  33351. _this.subMeshes = originalSubMeshes;
  33352. if (successCallback) {
  33353. successCallback(_this);
  33354. }
  33355. });
  33356. return this;
  33357. };
  33358. Mesh.prototype.serialize = function (serializationObject) {
  33359. serializationObject.name = this.name;
  33360. serializationObject.id = this.id;
  33361. serializationObject.type = this.getClassName();
  33362. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33363. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33364. }
  33365. serializationObject.position = this.position.asArray();
  33366. if (this.rotationQuaternion) {
  33367. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33368. }
  33369. else if (this.rotation) {
  33370. serializationObject.rotation = this.rotation.asArray();
  33371. }
  33372. serializationObject.scaling = this.scaling.asArray();
  33373. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33374. serializationObject.isEnabled = this.isEnabled(false);
  33375. serializationObject.isVisible = this.isVisible;
  33376. serializationObject.infiniteDistance = this.infiniteDistance;
  33377. serializationObject.pickable = this.isPickable;
  33378. serializationObject.receiveShadows = this.receiveShadows;
  33379. serializationObject.billboardMode = this.billboardMode;
  33380. serializationObject.visibility = this.visibility;
  33381. serializationObject.checkCollisions = this.checkCollisions;
  33382. serializationObject.isBlocker = this.isBlocker;
  33383. // Parent
  33384. if (this.parent) {
  33385. serializationObject.parentId = this.parent.id;
  33386. }
  33387. // Geometry
  33388. serializationObject.isUnIndexed = this.isUnIndexed;
  33389. var geometry = this._geometry;
  33390. if (geometry) {
  33391. var geometryId = geometry.id;
  33392. serializationObject.geometryId = geometryId;
  33393. // SubMeshes
  33394. serializationObject.subMeshes = [];
  33395. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33396. var subMesh = this.subMeshes[subIndex];
  33397. serializationObject.subMeshes.push({
  33398. materialIndex: subMesh.materialIndex,
  33399. verticesStart: subMesh.verticesStart,
  33400. verticesCount: subMesh.verticesCount,
  33401. indexStart: subMesh.indexStart,
  33402. indexCount: subMesh.indexCount
  33403. });
  33404. }
  33405. }
  33406. // Material
  33407. if (this.material) {
  33408. serializationObject.materialId = this.material.id;
  33409. }
  33410. else {
  33411. this.material = null;
  33412. }
  33413. // Morph targets
  33414. if (this.morphTargetManager) {
  33415. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33416. }
  33417. // Skeleton
  33418. if (this.skeleton) {
  33419. serializationObject.skeletonId = this.skeleton.id;
  33420. }
  33421. // Physics
  33422. //TODO implement correct serialization for physics impostors.
  33423. var impostor = this.getPhysicsImpostor();
  33424. if (impostor) {
  33425. serializationObject.physicsMass = impostor.getParam("mass");
  33426. serializationObject.physicsFriction = impostor.getParam("friction");
  33427. serializationObject.physicsRestitution = impostor.getParam("mass");
  33428. serializationObject.physicsImpostor = impostor.type;
  33429. }
  33430. // Metadata
  33431. if (this.metadata) {
  33432. serializationObject.metadata = this.metadata;
  33433. }
  33434. // Instances
  33435. serializationObject.instances = [];
  33436. for (var index = 0; index < this.instances.length; index++) {
  33437. var instance = this.instances[index];
  33438. var serializationInstance = {
  33439. name: instance.name,
  33440. id: instance.id,
  33441. position: instance.position.asArray(),
  33442. scaling: instance.scaling.asArray()
  33443. };
  33444. if (instance.rotationQuaternion) {
  33445. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33446. }
  33447. else if (instance.rotation) {
  33448. serializationInstance.rotation = instance.rotation.asArray();
  33449. }
  33450. serializationObject.instances.push(serializationInstance);
  33451. // Animations
  33452. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33453. serializationInstance.ranges = instance.serializeAnimationRanges();
  33454. }
  33455. //
  33456. // Animations
  33457. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33458. serializationObject.ranges = this.serializeAnimationRanges();
  33459. // Layer mask
  33460. serializationObject.layerMask = this.layerMask;
  33461. // Alpha
  33462. serializationObject.alphaIndex = this.alphaIndex;
  33463. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33464. // Overlay
  33465. serializationObject.overlayAlpha = this.overlayAlpha;
  33466. serializationObject.overlayColor = this.overlayColor.asArray();
  33467. serializationObject.renderOverlay = this.renderOverlay;
  33468. // Fog
  33469. serializationObject.applyFog = this.applyFog;
  33470. // Action Manager
  33471. if (this.actionManager) {
  33472. serializationObject.actions = this.actionManager.serialize(this.name);
  33473. }
  33474. };
  33475. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33476. if (!this.geometry) {
  33477. return;
  33478. }
  33479. this._markSubMeshesAsAttributesDirty();
  33480. var morphTargetManager = this._morphTargetManager;
  33481. if (morphTargetManager && morphTargetManager.vertexCount) {
  33482. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33483. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33484. this.morphTargetManager = null;
  33485. return;
  33486. }
  33487. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33488. var morphTarget = morphTargetManager.getActiveTarget(index);
  33489. var positions = morphTarget.getPositions();
  33490. if (!positions) {
  33491. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33492. return;
  33493. }
  33494. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33495. var normals = morphTarget.getNormals();
  33496. if (normals) {
  33497. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33498. }
  33499. var tangents = morphTarget.getTangents();
  33500. if (tangents) {
  33501. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33502. }
  33503. }
  33504. }
  33505. else {
  33506. var index = 0;
  33507. // Positions
  33508. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33509. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33510. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33511. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33512. }
  33513. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33514. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33515. }
  33516. index++;
  33517. }
  33518. }
  33519. };
  33520. // Statics
  33521. /**
  33522. * Returns a new Mesh object parsed from the source provided.
  33523. * The parameter `parsedMesh` is the source.
  33524. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33525. */
  33526. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33527. var mesh;
  33528. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33529. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33530. }
  33531. else {
  33532. mesh = new Mesh(parsedMesh.name, scene);
  33533. }
  33534. mesh.id = parsedMesh.id;
  33535. if (BABYLON.Tags) {
  33536. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33537. }
  33538. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33539. if (parsedMesh.metadata !== undefined) {
  33540. mesh.metadata = parsedMesh.metadata;
  33541. }
  33542. if (parsedMesh.rotationQuaternion) {
  33543. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33544. }
  33545. else if (parsedMesh.rotation) {
  33546. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33547. }
  33548. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33549. if (parsedMesh.localMatrix) {
  33550. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33551. }
  33552. else if (parsedMesh.pivotMatrix) {
  33553. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33554. }
  33555. mesh.setEnabled(parsedMesh.isEnabled);
  33556. mesh.isVisible = parsedMesh.isVisible;
  33557. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33558. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33559. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33560. if (parsedMesh.applyFog !== undefined) {
  33561. mesh.applyFog = parsedMesh.applyFog;
  33562. }
  33563. if (parsedMesh.pickable !== undefined) {
  33564. mesh.isPickable = parsedMesh.pickable;
  33565. }
  33566. if (parsedMesh.alphaIndex !== undefined) {
  33567. mesh.alphaIndex = parsedMesh.alphaIndex;
  33568. }
  33569. mesh.receiveShadows = parsedMesh.receiveShadows;
  33570. mesh.billboardMode = parsedMesh.billboardMode;
  33571. if (parsedMesh.visibility !== undefined) {
  33572. mesh.visibility = parsedMesh.visibility;
  33573. }
  33574. mesh.checkCollisions = parsedMesh.checkCollisions;
  33575. if (parsedMesh.isBlocker !== undefined) {
  33576. mesh.isBlocker = parsedMesh.isBlocker;
  33577. }
  33578. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33579. // freezeWorldMatrix
  33580. if (parsedMesh.freezeWorldMatrix) {
  33581. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33582. }
  33583. // Parent
  33584. if (parsedMesh.parentId) {
  33585. mesh._waitingParentId = parsedMesh.parentId;
  33586. }
  33587. // Actions
  33588. if (parsedMesh.actions !== undefined) {
  33589. mesh._waitingActions = parsedMesh.actions;
  33590. }
  33591. // Overlay
  33592. if (parsedMesh.overlayAlpha !== undefined) {
  33593. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33594. }
  33595. if (parsedMesh.overlayColor !== undefined) {
  33596. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33597. }
  33598. if (parsedMesh.renderOverlay !== undefined) {
  33599. mesh.renderOverlay = parsedMesh.renderOverlay;
  33600. }
  33601. // Geometry
  33602. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33603. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33604. if (parsedMesh.delayLoadingFile) {
  33605. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33606. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33607. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33608. if (parsedMesh._binaryInfo) {
  33609. mesh._binaryInfo = parsedMesh._binaryInfo;
  33610. }
  33611. mesh._delayInfo = [];
  33612. if (parsedMesh.hasUVs) {
  33613. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33614. }
  33615. if (parsedMesh.hasUVs2) {
  33616. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33617. }
  33618. if (parsedMesh.hasUVs3) {
  33619. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33620. }
  33621. if (parsedMesh.hasUVs4) {
  33622. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33623. }
  33624. if (parsedMesh.hasUVs5) {
  33625. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33626. }
  33627. if (parsedMesh.hasUVs6) {
  33628. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33629. }
  33630. if (parsedMesh.hasColors) {
  33631. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33632. }
  33633. if (parsedMesh.hasMatricesIndices) {
  33634. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33635. }
  33636. if (parsedMesh.hasMatricesWeights) {
  33637. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33638. }
  33639. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33640. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33641. mesh._checkDelayState();
  33642. }
  33643. }
  33644. else {
  33645. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33646. }
  33647. // Material
  33648. if (parsedMesh.materialId) {
  33649. mesh.setMaterialByID(parsedMesh.materialId);
  33650. }
  33651. else {
  33652. mesh.material = null;
  33653. }
  33654. // Morph targets
  33655. if (parsedMesh.morphTargetManagerId > -1) {
  33656. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33657. }
  33658. // Skeleton
  33659. if (parsedMesh.skeletonId > -1) {
  33660. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33661. if (parsedMesh.numBoneInfluencers) {
  33662. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33663. }
  33664. }
  33665. // Animations
  33666. if (parsedMesh.animations) {
  33667. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33668. var parsedAnimation = parsedMesh.animations[animationIndex];
  33669. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33670. }
  33671. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33672. }
  33673. if (parsedMesh.autoAnimate) {
  33674. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33675. }
  33676. // Layer Mask
  33677. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33678. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33679. }
  33680. else {
  33681. mesh.layerMask = 0x0FFFFFFF;
  33682. }
  33683. // Physics
  33684. if (parsedMesh.physicsImpostor) {
  33685. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33686. mass: parsedMesh.physicsMass,
  33687. friction: parsedMesh.physicsFriction,
  33688. restitution: parsedMesh.physicsRestitution
  33689. }, scene);
  33690. }
  33691. // Instances
  33692. if (parsedMesh.instances) {
  33693. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33694. var parsedInstance = parsedMesh.instances[index];
  33695. var instance = mesh.createInstance(parsedInstance.name);
  33696. if (parsedInstance.id) {
  33697. instance.id = parsedInstance.id;
  33698. }
  33699. if (BABYLON.Tags) {
  33700. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33701. }
  33702. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33703. if (parsedInstance.parentId) {
  33704. instance._waitingParentId = parsedInstance.parentId;
  33705. }
  33706. if (parsedInstance.rotationQuaternion) {
  33707. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33708. }
  33709. else if (parsedInstance.rotation) {
  33710. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33711. }
  33712. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33713. instance.checkCollisions = mesh.checkCollisions;
  33714. if (parsedMesh.animations) {
  33715. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33716. parsedAnimation = parsedMesh.animations[animationIndex];
  33717. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33718. }
  33719. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33720. if (parsedMesh.autoAnimate) {
  33721. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33722. }
  33723. }
  33724. }
  33725. }
  33726. return mesh;
  33727. };
  33728. /**
  33729. * Creates a ribbon mesh.
  33730. * Please consider using the same method from the MeshBuilder class instead.
  33731. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33732. *
  33733. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33734. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33735. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33736. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33737. * 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.
  33738. * 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.
  33739. * 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
  33740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33741. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33743. */
  33744. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33745. if (closeArray === void 0) { closeArray = false; }
  33746. if (updatable === void 0) { updatable = false; }
  33747. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33748. pathArray: pathArray,
  33749. closeArray: closeArray,
  33750. closePath: closePath,
  33751. offset: offset,
  33752. updatable: updatable,
  33753. sideOrientation: sideOrientation,
  33754. instance: instance
  33755. }, scene);
  33756. };
  33757. /**
  33758. * Creates a plane polygonal mesh. By default, this is a disc.
  33759. * Please consider using the same method from the MeshBuilder class instead.
  33760. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33761. * 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.
  33762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33763. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33765. */
  33766. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33767. if (scene === void 0) { scene = null; }
  33768. var options = {
  33769. radius: radius,
  33770. tessellation: tessellation,
  33771. sideOrientation: sideOrientation,
  33772. updatable: updatable
  33773. };
  33774. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33775. };
  33776. /**
  33777. * Creates a box mesh.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. * The parameter `size` sets the size (float) of each box side (default 1).
  33780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33781. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33783. */
  33784. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33785. if (scene === void 0) { scene = null; }
  33786. var options = {
  33787. size: size,
  33788. sideOrientation: sideOrientation,
  33789. updatable: updatable
  33790. };
  33791. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33792. };
  33793. /**
  33794. * Creates a sphere mesh.
  33795. * Please consider using the same method from the MeshBuilder class instead.
  33796. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33797. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33799. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33801. */
  33802. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33803. var options = {
  33804. segments: segments,
  33805. diameterX: diameter,
  33806. diameterY: diameter,
  33807. diameterZ: diameter,
  33808. sideOrientation: sideOrientation,
  33809. updatable: updatable
  33810. };
  33811. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33812. };
  33813. /**
  33814. * Creates a cylinder or a cone mesh.
  33815. * Please consider using the same method from the MeshBuilder class instead.
  33816. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33817. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33818. * 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.
  33819. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33820. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33822. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33824. */
  33825. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33826. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33827. if (scene !== undefined) {
  33828. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33829. updatable = scene;
  33830. }
  33831. scene = subdivisions;
  33832. subdivisions = 1;
  33833. }
  33834. var options = {
  33835. height: height,
  33836. diameterTop: diameterTop,
  33837. diameterBottom: diameterBottom,
  33838. tessellation: tessellation,
  33839. subdivisions: subdivisions,
  33840. sideOrientation: sideOrientation,
  33841. updatable: updatable
  33842. };
  33843. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33844. };
  33845. // Torus (Code from SharpDX.org)
  33846. /**
  33847. * Creates a torus mesh.
  33848. * Please consider using the same method from the MeshBuilder class instead.
  33849. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33850. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33851. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33853. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33855. */
  33856. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33857. var options = {
  33858. diameter: diameter,
  33859. thickness: thickness,
  33860. tessellation: tessellation,
  33861. sideOrientation: sideOrientation,
  33862. updatable: updatable
  33863. };
  33864. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33865. };
  33866. /**
  33867. * Creates a torus knot mesh.
  33868. * Please consider using the same method from the MeshBuilder class instead.
  33869. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33870. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33871. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33872. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33874. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33876. */
  33877. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33878. var options = {
  33879. radius: radius,
  33880. tube: tube,
  33881. radialSegments: radialSegments,
  33882. tubularSegments: tubularSegments,
  33883. p: p,
  33884. q: q,
  33885. sideOrientation: sideOrientation,
  33886. updatable: updatable
  33887. };
  33888. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33889. };
  33890. /**
  33891. * Creates a line mesh.
  33892. * Please consider using the same method from the MeshBuilder class instead.
  33893. * 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.
  33894. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33895. * The parameter `points` is an array successive Vector3.
  33896. * 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
  33897. * When updating an instance, remember that only point positions can change, not the number of points.
  33898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33899. */
  33900. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33901. if (scene === void 0) { scene = null; }
  33902. if (updatable === void 0) { updatable = false; }
  33903. if (instance === void 0) { instance = null; }
  33904. var options = {
  33905. points: points,
  33906. updatable: updatable,
  33907. instance: instance
  33908. };
  33909. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33910. };
  33911. /**
  33912. * Creates a dashed line mesh.
  33913. * Please consider using the same method from the MeshBuilder class instead.
  33914. * 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.
  33915. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33916. * The parameter `points` is an array successive Vector3.
  33917. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33918. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33919. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33920. * 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
  33921. * When updating an instance, remember that only point positions can change, not the number of points.
  33922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33923. */
  33924. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33925. if (scene === void 0) { scene = null; }
  33926. var options = {
  33927. points: points,
  33928. dashSize: dashSize,
  33929. gapSize: gapSize,
  33930. dashNb: dashNb,
  33931. updatable: updatable,
  33932. instance: instance
  33933. };
  33934. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33935. };
  33936. /**
  33937. * Creates a polygon mesh.
  33938. * Please consider using the same method from the MeshBuilder class instead.
  33939. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33940. * 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.
  33941. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33943. * Remember you can only change the shape positions, not their number when updating a polygon.
  33944. */
  33945. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33946. var options = {
  33947. shape: shape,
  33948. holes: holes,
  33949. updatable: updatable,
  33950. sideOrientation: sideOrientation
  33951. };
  33952. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33953. };
  33954. /**
  33955. * Creates an extruded polygon mesh, with depth in the Y direction.
  33956. * Please consider using the same method from the MeshBuilder class instead.
  33957. */
  33958. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33959. var options = {
  33960. shape: shape,
  33961. holes: holes,
  33962. depth: depth,
  33963. updatable: updatable,
  33964. sideOrientation: sideOrientation
  33965. };
  33966. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33967. };
  33968. /**
  33969. * Creates an extruded shape mesh.
  33970. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33971. * Please consider using the same method from the MeshBuilder class instead.
  33972. *
  33973. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33974. * 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
  33975. * extruded along the Z axis.
  33976. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33977. * 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.
  33978. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33979. * 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
  33980. * 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
  33981. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33983. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33985. */
  33986. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33987. if (scene === void 0) { scene = null; }
  33988. var options = {
  33989. shape: shape,
  33990. path: path,
  33991. scale: scale,
  33992. rotation: rotation,
  33993. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33994. sideOrientation: sideOrientation,
  33995. instance: instance,
  33996. updatable: updatable
  33997. };
  33998. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33999. };
  34000. /**
  34001. * Creates an custom extruded shape mesh.
  34002. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34003. * Please consider using the same method from the MeshBuilder class instead.
  34004. *
  34005. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34006. * 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
  34007. * extruded along the Z axis.
  34008. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34009. * 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
  34010. * and the distance of this point from the begining of the path :
  34011. * ```javascript
  34012. * var rotationFunction = function(i, distance) {
  34013. * // do things
  34014. * return rotationValue; }
  34015. * ```
  34016. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34017. * 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
  34018. * and the distance of this point from the begining of the path :
  34019. * ```javascript
  34020. * var scaleFunction = function(i, distance) {
  34021. * // do things
  34022. * return scaleValue;}
  34023. * ```
  34024. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34025. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34026. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34027. * 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
  34028. * 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
  34029. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34031. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34033. */
  34034. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34035. var options = {
  34036. shape: shape,
  34037. path: path,
  34038. scaleFunction: scaleFunction,
  34039. rotationFunction: rotationFunction,
  34040. ribbonCloseArray: ribbonCloseArray,
  34041. ribbonClosePath: ribbonClosePath,
  34042. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34043. sideOrientation: sideOrientation,
  34044. instance: instance,
  34045. updatable: updatable
  34046. };
  34047. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34048. };
  34049. /**
  34050. * Creates lathe mesh.
  34051. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34052. * Please consider using the same method from the MeshBuilder class instead.
  34053. * 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
  34054. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34055. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34056. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34057. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34058. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34060. */
  34061. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34062. var options = {
  34063. shape: shape,
  34064. radius: radius,
  34065. tessellation: tessellation,
  34066. sideOrientation: sideOrientation,
  34067. updatable: updatable
  34068. };
  34069. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34070. };
  34071. /**
  34072. * Creates a plane mesh.
  34073. * Please consider using the same method from the MeshBuilder class instead.
  34074. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34075. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34076. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34078. */
  34079. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34080. var options = {
  34081. size: size,
  34082. width: size,
  34083. height: size,
  34084. sideOrientation: sideOrientation,
  34085. updatable: updatable
  34086. };
  34087. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34088. };
  34089. /**
  34090. * Creates a ground mesh.
  34091. * Please consider using the same method from the MeshBuilder class instead.
  34092. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34093. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34095. */
  34096. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34097. var options = {
  34098. width: width,
  34099. height: height,
  34100. subdivisions: subdivisions,
  34101. updatable: updatable
  34102. };
  34103. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34104. };
  34105. /**
  34106. * Creates a tiled ground mesh.
  34107. * Please consider using the same method from the MeshBuilder class instead.
  34108. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34109. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34110. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34111. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34112. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34113. * numbers of subdivisions on the ground width and height of each tile.
  34114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34115. */
  34116. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34117. var options = {
  34118. xmin: xmin,
  34119. zmin: zmin,
  34120. xmax: xmax,
  34121. zmax: zmax,
  34122. subdivisions: subdivisions,
  34123. precision: precision,
  34124. updatable: updatable
  34125. };
  34126. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34127. };
  34128. /**
  34129. * Creates a ground mesh from a height map.
  34130. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34131. * Please consider using the same method from the MeshBuilder class instead.
  34132. * The parameter `url` sets the URL of the height map image resource.
  34133. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34134. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34135. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34136. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34137. * 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).
  34138. * This function is passed the newly built mesh :
  34139. * ```javascript
  34140. * function(mesh) { // do things
  34141. * return; }
  34142. * ```
  34143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34144. */
  34145. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34146. var options = {
  34147. width: width,
  34148. height: height,
  34149. subdivisions: subdivisions,
  34150. minHeight: minHeight,
  34151. maxHeight: maxHeight,
  34152. updatable: updatable,
  34153. onReady: onReady
  34154. };
  34155. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34156. };
  34157. /**
  34158. * Creates a tube mesh.
  34159. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34160. * Please consider using the same method from the MeshBuilder class instead.
  34161. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34162. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34163. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34164. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34165. * 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.
  34166. * It must return a radius value (positive float) :
  34167. * ```javascript
  34168. * var radiusFunction = function(i, distance) {
  34169. * // do things
  34170. * return radius; }
  34171. * ```
  34172. * 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
  34173. * 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
  34174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34175. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34177. */
  34178. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34179. var options = {
  34180. path: path,
  34181. radius: radius,
  34182. tessellation: tessellation,
  34183. radiusFunction: radiusFunction,
  34184. arc: 1,
  34185. cap: cap,
  34186. updatable: updatable,
  34187. sideOrientation: sideOrientation,
  34188. instance: instance
  34189. };
  34190. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34191. };
  34192. /**
  34193. * Creates a polyhedron mesh.
  34194. * Please consider using the same method from the MeshBuilder class instead.
  34195. * 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
  34196. * to choose the wanted type.
  34197. * The parameter `size` (positive float, default 1) sets the polygon size.
  34198. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34199. * 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`.
  34200. * 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
  34201. * 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)`).
  34202. * 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
  34203. * 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.
  34204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34205. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34207. */
  34208. Mesh.CreatePolyhedron = function (name, options, scene) {
  34209. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34210. };
  34211. /**
  34212. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34213. * Please consider using the same method from the MeshBuilder class instead.
  34214. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34215. * 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`).
  34216. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34217. * 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.
  34218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34219. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34221. */
  34222. Mesh.CreateIcoSphere = function (name, options, scene) {
  34223. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34224. };
  34225. /**
  34226. * Creates a decal mesh.
  34227. * Please consider using the same method from the MeshBuilder class instead.
  34228. * 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.
  34229. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34230. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34231. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34232. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34233. */
  34234. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34235. var options = {
  34236. position: position,
  34237. normal: normal,
  34238. size: size,
  34239. angle: angle
  34240. };
  34241. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34242. };
  34243. // Skeletons
  34244. /**
  34245. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34246. */
  34247. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34248. if (!this._sourcePositions) {
  34249. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34250. if (!source) {
  34251. return this._sourcePositions;
  34252. }
  34253. this._sourcePositions = new Float32Array(source);
  34254. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34255. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34256. }
  34257. }
  34258. return this._sourcePositions;
  34259. };
  34260. /**
  34261. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34262. */
  34263. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34264. if (!this._sourceNormals) {
  34265. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34266. if (!source) {
  34267. return this._sourceNormals;
  34268. }
  34269. this._sourceNormals = new Float32Array(source);
  34270. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34271. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34272. }
  34273. }
  34274. return this._sourceNormals;
  34275. };
  34276. /**
  34277. * Updates the vertex buffer by applying transformation from the bones.
  34278. * Returns the Mesh.
  34279. *
  34280. * @param {skeleton} skeleton to apply
  34281. */
  34282. Mesh.prototype.applySkeleton = function (skeleton) {
  34283. if (!this.geometry) {
  34284. return this;
  34285. }
  34286. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34287. return this;
  34288. }
  34289. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34290. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34291. return this;
  34292. }
  34293. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34294. return this;
  34295. }
  34296. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34297. return this;
  34298. }
  34299. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34300. return this;
  34301. }
  34302. if (!this._sourcePositions) {
  34303. var submeshes = this.subMeshes.slice();
  34304. this.setPositionsForCPUSkinning();
  34305. this.subMeshes = submeshes;
  34306. }
  34307. if (!this._sourceNormals) {
  34308. this.setNormalsForCPUSkinning();
  34309. }
  34310. // positionsData checks for not being Float32Array will only pass at most once
  34311. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34312. if (!positionsData) {
  34313. return this;
  34314. }
  34315. if (!(positionsData instanceof Float32Array)) {
  34316. positionsData = new Float32Array(positionsData);
  34317. }
  34318. // normalsData checks for not being Float32Array will only pass at most once
  34319. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34320. if (!normalsData) {
  34321. return this;
  34322. }
  34323. if (!(normalsData instanceof Float32Array)) {
  34324. normalsData = new Float32Array(normalsData);
  34325. }
  34326. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34327. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34328. if (!matricesWeightsData || !matricesIndicesData) {
  34329. return this;
  34330. }
  34331. var needExtras = this.numBoneInfluencers > 4;
  34332. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34333. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34334. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34335. var tempVector3 = BABYLON.Vector3.Zero();
  34336. var finalMatrix = new BABYLON.Matrix();
  34337. var tempMatrix = new BABYLON.Matrix();
  34338. var matWeightIdx = 0;
  34339. var inf;
  34340. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34341. var weight;
  34342. for (inf = 0; inf < 4; inf++) {
  34343. weight = matricesWeightsData[matWeightIdx + inf];
  34344. if (weight > 0) {
  34345. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34346. finalMatrix.addToSelf(tempMatrix);
  34347. }
  34348. else
  34349. break;
  34350. }
  34351. if (needExtras) {
  34352. for (inf = 0; inf < 4; inf++) {
  34353. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34354. if (weight > 0) {
  34355. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34356. finalMatrix.addToSelf(tempMatrix);
  34357. }
  34358. else
  34359. break;
  34360. }
  34361. }
  34362. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34363. tempVector3.toArray(positionsData, index);
  34364. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34365. tempVector3.toArray(normalsData, index);
  34366. finalMatrix.reset();
  34367. }
  34368. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34369. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34370. return this;
  34371. };
  34372. // Tools
  34373. /**
  34374. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34375. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34376. */
  34377. Mesh.MinMax = function (meshes) {
  34378. var minVector = null;
  34379. var maxVector = null;
  34380. meshes.forEach(function (mesh, index, array) {
  34381. var boundingInfo = mesh.getBoundingInfo();
  34382. var boundingBox = boundingInfo.boundingBox;
  34383. if (!minVector || !maxVector) {
  34384. minVector = boundingBox.minimumWorld;
  34385. maxVector = boundingBox.maximumWorld;
  34386. }
  34387. else {
  34388. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34389. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34390. }
  34391. });
  34392. if (!minVector || !maxVector) {
  34393. return {
  34394. min: BABYLON.Vector3.Zero(),
  34395. max: BABYLON.Vector3.Zero()
  34396. };
  34397. }
  34398. return {
  34399. min: minVector,
  34400. max: maxVector
  34401. };
  34402. };
  34403. /**
  34404. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34405. */
  34406. Mesh.Center = function (meshesOrMinMaxVector) {
  34407. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34408. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34409. };
  34410. /**
  34411. * Merge the array of meshes into a single mesh for performance reasons.
  34412. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34413. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34414. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34415. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34416. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34417. */
  34418. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34419. if (disposeSource === void 0) { disposeSource = true; }
  34420. var index;
  34421. if (!allow32BitsIndices) {
  34422. var totalVertices = 0;
  34423. // Counting vertices
  34424. for (index = 0; index < meshes.length; index++) {
  34425. if (meshes[index]) {
  34426. totalVertices += meshes[index].getTotalVertices();
  34427. if (totalVertices > 65536) {
  34428. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34429. return null;
  34430. }
  34431. }
  34432. }
  34433. }
  34434. // Merge
  34435. var vertexData = null;
  34436. var otherVertexData;
  34437. var indiceArray = new Array();
  34438. var source = null;
  34439. for (index = 0; index < meshes.length; index++) {
  34440. if (meshes[index]) {
  34441. meshes[index].computeWorldMatrix(true);
  34442. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34443. otherVertexData.transform(meshes[index].getWorldMatrix());
  34444. if (vertexData) {
  34445. vertexData.merge(otherVertexData);
  34446. }
  34447. else {
  34448. vertexData = otherVertexData;
  34449. source = meshes[index];
  34450. }
  34451. if (subdivideWithSubMeshes) {
  34452. indiceArray.push(meshes[index].getTotalIndices());
  34453. }
  34454. }
  34455. }
  34456. source = source;
  34457. if (!meshSubclass) {
  34458. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34459. }
  34460. vertexData.applyToMesh(meshSubclass);
  34461. // Setting properties
  34462. meshSubclass.material = source.material;
  34463. meshSubclass.checkCollisions = source.checkCollisions;
  34464. // Cleaning
  34465. if (disposeSource) {
  34466. for (index = 0; index < meshes.length; index++) {
  34467. if (meshes[index]) {
  34468. meshes[index].dispose();
  34469. }
  34470. }
  34471. }
  34472. // Subdivide
  34473. if (subdivideWithSubMeshes) {
  34474. //-- removal of global submesh
  34475. meshSubclass.releaseSubMeshes();
  34476. index = 0;
  34477. var offset = 0;
  34478. //-- apply subdivision according to index table
  34479. while (index < indiceArray.length) {
  34480. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34481. offset += indiceArray[index];
  34482. index++;
  34483. }
  34484. }
  34485. return meshSubclass;
  34486. };
  34487. // Consts
  34488. Mesh._FRONTSIDE = 0;
  34489. Mesh._BACKSIDE = 1;
  34490. Mesh._DOUBLESIDE = 2;
  34491. Mesh._DEFAULTSIDE = 0;
  34492. Mesh._NO_CAP = 0;
  34493. Mesh._CAP_START = 1;
  34494. Mesh._CAP_END = 2;
  34495. Mesh._CAP_ALL = 3;
  34496. return Mesh;
  34497. }(BABYLON.AbstractMesh));
  34498. BABYLON.Mesh = Mesh;
  34499. })(BABYLON || (BABYLON = {}));
  34500. //# sourceMappingURL=babylon.mesh.js.map
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var BaseSubMesh = /** @class */ (function () {
  34504. function BaseSubMesh() {
  34505. }
  34506. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34507. get: function () {
  34508. return this._materialEffect;
  34509. },
  34510. enumerable: true,
  34511. configurable: true
  34512. });
  34513. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34514. if (defines === void 0) { defines = null; }
  34515. if (this._materialEffect === effect) {
  34516. if (!effect) {
  34517. this._materialDefines = null;
  34518. }
  34519. return;
  34520. }
  34521. this._materialDefines = defines;
  34522. this._materialEffect = effect;
  34523. };
  34524. return BaseSubMesh;
  34525. }());
  34526. BABYLON.BaseSubMesh = BaseSubMesh;
  34527. var SubMesh = /** @class */ (function (_super) {
  34528. __extends(SubMesh, _super);
  34529. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34530. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34531. var _this = _super.call(this) || this;
  34532. _this.materialIndex = materialIndex;
  34533. _this.verticesStart = verticesStart;
  34534. _this.verticesCount = verticesCount;
  34535. _this.indexStart = indexStart;
  34536. _this.indexCount = indexCount;
  34537. _this._renderId = 0;
  34538. _this._mesh = mesh;
  34539. _this._renderingMesh = renderingMesh || mesh;
  34540. mesh.subMeshes.push(_this);
  34541. _this._trianglePlanes = [];
  34542. _this._id = mesh.subMeshes.length - 1;
  34543. if (createBoundingBox) {
  34544. _this.refreshBoundingInfo();
  34545. mesh.computeWorldMatrix(true);
  34546. }
  34547. return _this;
  34548. }
  34549. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34550. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34551. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34552. };
  34553. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34554. get: function () {
  34555. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34556. },
  34557. enumerable: true,
  34558. configurable: true
  34559. });
  34560. /**
  34561. * Returns the submesh BoudingInfo object.
  34562. */
  34563. SubMesh.prototype.getBoundingInfo = function () {
  34564. if (this.IsGlobal) {
  34565. return this._mesh.getBoundingInfo();
  34566. }
  34567. return this._boundingInfo;
  34568. };
  34569. /**
  34570. * Sets the submesh BoundingInfo.
  34571. * Return the SubMesh.
  34572. */
  34573. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34574. this._boundingInfo = boundingInfo;
  34575. return this;
  34576. };
  34577. /**
  34578. * Returns the mesh of the current submesh.
  34579. */
  34580. SubMesh.prototype.getMesh = function () {
  34581. return this._mesh;
  34582. };
  34583. /**
  34584. * Returns the rendering mesh of the submesh.
  34585. */
  34586. SubMesh.prototype.getRenderingMesh = function () {
  34587. return this._renderingMesh;
  34588. };
  34589. /**
  34590. * Returns the submesh material.
  34591. */
  34592. SubMesh.prototype.getMaterial = function () {
  34593. var rootMaterial = this._renderingMesh.material;
  34594. if (rootMaterial === null || rootMaterial === undefined) {
  34595. return this._mesh.getScene().defaultMaterial;
  34596. }
  34597. else if (rootMaterial.getSubMaterial) {
  34598. var multiMaterial = rootMaterial;
  34599. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34600. if (this._currentMaterial !== effectiveMaterial) {
  34601. this._currentMaterial = effectiveMaterial;
  34602. this._materialDefines = null;
  34603. }
  34604. return effectiveMaterial;
  34605. }
  34606. return rootMaterial;
  34607. };
  34608. // Methods
  34609. /**
  34610. * Sets a new updated BoundingInfo object to the submesh.
  34611. * Returns the SubMesh.
  34612. */
  34613. SubMesh.prototype.refreshBoundingInfo = function () {
  34614. this._lastColliderWorldVertices = null;
  34615. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34616. return this;
  34617. }
  34618. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34619. if (!data) {
  34620. this._boundingInfo = this._mesh.getBoundingInfo();
  34621. return this;
  34622. }
  34623. var indices = this._renderingMesh.getIndices();
  34624. var extend;
  34625. //is this the only submesh?
  34626. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34627. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34628. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34629. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34630. }
  34631. else {
  34632. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34633. }
  34634. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34635. return this;
  34636. };
  34637. SubMesh.prototype._checkCollision = function (collider) {
  34638. var boundingInfo = this.getBoundingInfo();
  34639. return boundingInfo._checkCollision(collider);
  34640. };
  34641. /**
  34642. * Updates the submesh BoundingInfo.
  34643. * Returns the Submesh.
  34644. */
  34645. SubMesh.prototype.updateBoundingInfo = function (world) {
  34646. var boundingInfo = this.getBoundingInfo();
  34647. if (!boundingInfo) {
  34648. this.refreshBoundingInfo();
  34649. boundingInfo = this.getBoundingInfo();
  34650. }
  34651. boundingInfo.update(world);
  34652. return this;
  34653. };
  34654. /**
  34655. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34656. * Boolean returned.
  34657. */
  34658. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34659. var boundingInfo = this.getBoundingInfo();
  34660. if (!boundingInfo) {
  34661. return false;
  34662. }
  34663. return boundingInfo.isInFrustum(frustumPlanes);
  34664. };
  34665. /**
  34666. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34667. * Boolean returned.
  34668. */
  34669. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34670. var boundingInfo = this.getBoundingInfo();
  34671. if (!boundingInfo) {
  34672. return false;
  34673. }
  34674. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34675. };
  34676. /**
  34677. * Renders the submesh.
  34678. * Returns it.
  34679. */
  34680. SubMesh.prototype.render = function (enableAlphaMode) {
  34681. this._renderingMesh.render(this, enableAlphaMode);
  34682. return this;
  34683. };
  34684. /**
  34685. * Returns a new Index Buffer.
  34686. * Type returned : WebGLBuffer.
  34687. */
  34688. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34689. if (!this._linesIndexBuffer) {
  34690. var linesIndices = [];
  34691. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34692. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34693. }
  34694. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34695. this.linesIndexCount = linesIndices.length;
  34696. }
  34697. return this._linesIndexBuffer;
  34698. };
  34699. /**
  34700. * True is the passed Ray intersects the submesh bounding box.
  34701. * Boolean returned.
  34702. */
  34703. SubMesh.prototype.canIntersects = function (ray) {
  34704. var boundingInfo = this.getBoundingInfo();
  34705. if (!boundingInfo) {
  34706. return false;
  34707. }
  34708. return ray.intersectsBox(boundingInfo.boundingBox);
  34709. };
  34710. /**
  34711. * Returns an object IntersectionInfo.
  34712. */
  34713. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34714. var intersectInfo = null;
  34715. var material = this.getMaterial();
  34716. if (!material) {
  34717. return null;
  34718. }
  34719. switch (material.fillMode) {
  34720. case BABYLON.Material.PointListDrawMode:
  34721. case BABYLON.Material.LineListDrawMode:
  34722. case BABYLON.Material.LineLoopDrawMode:
  34723. case BABYLON.Material.LineStripDrawMode:
  34724. case BABYLON.Material.TriangleFanDrawMode:
  34725. case BABYLON.Material.TriangleStripDrawMode:
  34726. return null;
  34727. }
  34728. // LineMesh first as it's also a Mesh...
  34729. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34730. var lineMesh = this._mesh;
  34731. // Line test
  34732. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34733. var p0 = positions[indices[index]];
  34734. var p1 = positions[indices[index + 1]];
  34735. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34736. if (length < 0) {
  34737. continue;
  34738. }
  34739. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34740. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34741. if (fastCheck) {
  34742. break;
  34743. }
  34744. }
  34745. }
  34746. }
  34747. else {
  34748. // Triangles test
  34749. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34750. var p0 = positions[indices[index]];
  34751. var p1 = positions[indices[index + 1]];
  34752. var p2 = positions[indices[index + 2]];
  34753. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34754. if (currentIntersectInfo) {
  34755. if (currentIntersectInfo.distance < 0) {
  34756. continue;
  34757. }
  34758. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34759. intersectInfo = currentIntersectInfo;
  34760. intersectInfo.faceId = index / 3;
  34761. if (fastCheck) {
  34762. break;
  34763. }
  34764. }
  34765. }
  34766. }
  34767. }
  34768. return intersectInfo;
  34769. };
  34770. SubMesh.prototype._rebuild = function () {
  34771. if (this._linesIndexBuffer) {
  34772. this._linesIndexBuffer = null;
  34773. }
  34774. };
  34775. // Clone
  34776. /**
  34777. * Creates a new Submesh from the passed Mesh.
  34778. */
  34779. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34780. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34781. if (!this.IsGlobal) {
  34782. var boundingInfo = this.getBoundingInfo();
  34783. if (!boundingInfo) {
  34784. return result;
  34785. }
  34786. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34787. }
  34788. return result;
  34789. };
  34790. // Dispose
  34791. /**
  34792. * Disposes the Submesh.
  34793. * Returns nothing.
  34794. */
  34795. SubMesh.prototype.dispose = function () {
  34796. if (this._linesIndexBuffer) {
  34797. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34798. this._linesIndexBuffer = null;
  34799. }
  34800. // Remove from mesh
  34801. var index = this._mesh.subMeshes.indexOf(this);
  34802. this._mesh.subMeshes.splice(index, 1);
  34803. };
  34804. // Statics
  34805. /**
  34806. * Creates a new Submesh from the passed parameters :
  34807. * - materialIndex (integer) : the index of the main mesh material.
  34808. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34809. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34810. * - mesh (Mesh) : the main mesh to create the submesh from.
  34811. * - renderingMesh (optional Mesh) : rendering mesh.
  34812. */
  34813. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34814. var minVertexIndex = Number.MAX_VALUE;
  34815. var maxVertexIndex = -Number.MAX_VALUE;
  34816. renderingMesh = (renderingMesh || mesh);
  34817. var indices = renderingMesh.getIndices();
  34818. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34819. var vertexIndex = indices[index];
  34820. if (vertexIndex < minVertexIndex)
  34821. minVertexIndex = vertexIndex;
  34822. if (vertexIndex > maxVertexIndex)
  34823. maxVertexIndex = vertexIndex;
  34824. }
  34825. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34826. };
  34827. return SubMesh;
  34828. }(BaseSubMesh));
  34829. BABYLON.SubMesh = SubMesh;
  34830. })(BABYLON || (BABYLON = {}));
  34831. //# sourceMappingURL=babylon.subMesh.js.map
  34832. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34833. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34834. s = arguments[i];
  34835. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34836. t[p] = s[p];
  34837. }
  34838. return t;
  34839. };
  34840. var BABYLON;
  34841. (function (BABYLON) {
  34842. /**
  34843. * Manages the defines for the Material
  34844. */
  34845. var MaterialDefines = /** @class */ (function () {
  34846. function MaterialDefines() {
  34847. this._isDirty = true;
  34848. /** @hidden */
  34849. this._areLightsDirty = true;
  34850. /** @hidden */
  34851. this._areAttributesDirty = true;
  34852. /** @hidden */
  34853. this._areTexturesDirty = true;
  34854. /** @hidden */
  34855. this._areFresnelDirty = true;
  34856. /** @hidden */
  34857. this._areMiscDirty = true;
  34858. /** @hidden */
  34859. this._areImageProcessingDirty = true;
  34860. /** @hidden */
  34861. this._normals = false;
  34862. /** @hidden */
  34863. this._uvs = false;
  34864. /** @hidden */
  34865. this._needNormals = false;
  34866. /** @hidden */
  34867. this._needUVs = false;
  34868. }
  34869. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34870. /**
  34871. * Specifies if the material needs to be re-calculated
  34872. */
  34873. get: function () {
  34874. return this._isDirty;
  34875. },
  34876. enumerable: true,
  34877. configurable: true
  34878. });
  34879. /**
  34880. * Marks the material to indicate that it has been re-calculated
  34881. */
  34882. MaterialDefines.prototype.markAsProcessed = function () {
  34883. this._isDirty = false;
  34884. this._areAttributesDirty = false;
  34885. this._areTexturesDirty = false;
  34886. this._areFresnelDirty = false;
  34887. this._areLightsDirty = false;
  34888. this._areMiscDirty = false;
  34889. this._areImageProcessingDirty = false;
  34890. };
  34891. /**
  34892. * Marks the material to indicate that it needs to be re-calculated
  34893. */
  34894. MaterialDefines.prototype.markAsUnprocessed = function () {
  34895. this._isDirty = true;
  34896. };
  34897. /**
  34898. * Marks the material to indicate all of its defines need to be re-calculated
  34899. */
  34900. MaterialDefines.prototype.markAllAsDirty = function () {
  34901. this._areTexturesDirty = true;
  34902. this._areAttributesDirty = true;
  34903. this._areLightsDirty = true;
  34904. this._areFresnelDirty = true;
  34905. this._areMiscDirty = true;
  34906. this._areImageProcessingDirty = true;
  34907. this._isDirty = true;
  34908. };
  34909. /**
  34910. * Marks the material to indicate that image processing needs to be re-calculated
  34911. */
  34912. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34913. this._areImageProcessingDirty = true;
  34914. this._isDirty = true;
  34915. };
  34916. /**
  34917. * Marks the material to indicate the lights need to be re-calculated
  34918. */
  34919. MaterialDefines.prototype.markAsLightDirty = function () {
  34920. this._areLightsDirty = true;
  34921. this._isDirty = true;
  34922. };
  34923. /**
  34924. * Marks the attribute state as changed
  34925. */
  34926. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34927. this._areAttributesDirty = true;
  34928. this._isDirty = true;
  34929. };
  34930. /**
  34931. * Marks the texture state as changed
  34932. */
  34933. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34934. this._areTexturesDirty = true;
  34935. this._isDirty = true;
  34936. };
  34937. /**
  34938. * Marks the fresnel state as changed
  34939. */
  34940. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34941. this._areFresnelDirty = true;
  34942. this._isDirty = true;
  34943. };
  34944. /**
  34945. * Marks the misc state as changed
  34946. */
  34947. MaterialDefines.prototype.markAsMiscDirty = function () {
  34948. this._areMiscDirty = true;
  34949. this._isDirty = true;
  34950. };
  34951. /**
  34952. * Rebuilds the material defines
  34953. */
  34954. MaterialDefines.prototype.rebuild = function () {
  34955. if (this._keys) {
  34956. delete this._keys;
  34957. }
  34958. this._keys = [];
  34959. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34960. var key = _a[_i];
  34961. if (key[0] === "_") {
  34962. continue;
  34963. }
  34964. this._keys.push(key);
  34965. }
  34966. };
  34967. /**
  34968. * Specifies if two material defines are equal
  34969. * @param other - A material define instance to compare to
  34970. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34971. */
  34972. MaterialDefines.prototype.isEqual = function (other) {
  34973. if (this._keys.length !== other._keys.length) {
  34974. return false;
  34975. }
  34976. for (var index = 0; index < this._keys.length; index++) {
  34977. var prop = this._keys[index];
  34978. if (this[prop] !== other[prop]) {
  34979. return false;
  34980. }
  34981. }
  34982. return true;
  34983. };
  34984. /**
  34985. * Clones this instance's defines to another instance
  34986. * @param other - material defines to clone values to
  34987. */
  34988. MaterialDefines.prototype.cloneTo = function (other) {
  34989. if (this._keys.length !== other._keys.length) {
  34990. other._keys = this._keys.slice(0);
  34991. }
  34992. for (var index = 0; index < this._keys.length; index++) {
  34993. var prop = this._keys[index];
  34994. other[prop] = this[prop];
  34995. }
  34996. };
  34997. /**
  34998. * Resets the material define values
  34999. */
  35000. MaterialDefines.prototype.reset = function () {
  35001. for (var index = 0; index < this._keys.length; index++) {
  35002. var prop = this._keys[index];
  35003. var type = typeof this[prop];
  35004. switch (type) {
  35005. case "number":
  35006. this[prop] = 0;
  35007. break;
  35008. case "string":
  35009. this[prop] = "";
  35010. break;
  35011. default:
  35012. this[prop] = false;
  35013. break;
  35014. }
  35015. }
  35016. };
  35017. /**
  35018. * Converts the material define values to a string
  35019. * @returns - String of material define information
  35020. */
  35021. MaterialDefines.prototype.toString = function () {
  35022. var result = "";
  35023. for (var index = 0; index < this._keys.length; index++) {
  35024. var prop = this._keys[index];
  35025. var value = this[prop];
  35026. var type = typeof value;
  35027. switch (type) {
  35028. case "number":
  35029. case "string":
  35030. result += "#define " + prop + " " + value + "\n";
  35031. break;
  35032. default:
  35033. if (value) {
  35034. result += "#define " + prop + "\n";
  35035. }
  35036. break;
  35037. }
  35038. }
  35039. return result;
  35040. };
  35041. return MaterialDefines;
  35042. }());
  35043. BABYLON.MaterialDefines = MaterialDefines;
  35044. /**
  35045. * Base class for the main features of a material in Babylon.js
  35046. */
  35047. var Material = /** @class */ (function () {
  35048. /**
  35049. * Creates a material instance
  35050. * @param name defines the name of the material
  35051. * @param scene defines the scene to reference
  35052. * @param doNotAdd specifies if the material should be added to the scene
  35053. */
  35054. function Material(name, scene, doNotAdd) {
  35055. /**
  35056. * Specifies if the ready state should be checked on each call
  35057. */
  35058. this.checkReadyOnEveryCall = false;
  35059. /**
  35060. * Specifies if the ready state should be checked once
  35061. */
  35062. this.checkReadyOnlyOnce = false;
  35063. /**
  35064. * The state of the material
  35065. */
  35066. this.state = "";
  35067. /**
  35068. * The alpha value of the material
  35069. */
  35070. this._alpha = 1.0;
  35071. /**
  35072. * Specifies if back face culling is enabled
  35073. */
  35074. this._backFaceCulling = true;
  35075. /**
  35076. * Specifies if the material should be serialized
  35077. */
  35078. this.doNotSerialize = false;
  35079. /**
  35080. * Specifies if the effect should be stored on sub meshes
  35081. */
  35082. this.storeEffectOnSubMeshes = false;
  35083. /**
  35084. * An event triggered when the material is disposed
  35085. */
  35086. this.onDisposeObservable = new BABYLON.Observable();
  35087. /**
  35088. * An event triggered when the material is bound
  35089. */
  35090. this.onBindObservable = new BABYLON.Observable();
  35091. /**
  35092. * An event triggered when the material is unbound
  35093. */
  35094. this.onUnBindObservable = new BABYLON.Observable();
  35095. /**
  35096. * Stores the value of the alpha mode
  35097. */
  35098. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35099. /**
  35100. * Stores the state of the need depth pre-pass value
  35101. */
  35102. this._needDepthPrePass = false;
  35103. /**
  35104. * Specifies if depth writing should be disabled
  35105. */
  35106. this.disableDepthWrite = false;
  35107. /**
  35108. * Specifies if depth writing should be forced
  35109. */
  35110. this.forceDepthWrite = false;
  35111. /**
  35112. * Specifies if there should be a separate pass for culling
  35113. */
  35114. this.separateCullingPass = false;
  35115. /**
  35116. * Stores the state specifing if fog should be enabled
  35117. */
  35118. this._fogEnabled = true;
  35119. /**
  35120. * Stores the size of points
  35121. */
  35122. this.pointSize = 1.0;
  35123. /**
  35124. * Stores the z offset value
  35125. */
  35126. this.zOffset = 0;
  35127. /**
  35128. * Specifies if the material was previously ready
  35129. */
  35130. this._wasPreviouslyReady = false;
  35131. /**
  35132. * Stores the fill mode state
  35133. */
  35134. this._fillMode = Material.TriangleFillMode;
  35135. this.name = name;
  35136. this.id = name || BABYLON.Tools.RandomId();
  35137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35138. this.uniqueId = this._scene.getUniqueId();
  35139. if (this._scene.useRightHandedSystem) {
  35140. this.sideOrientation = Material.ClockWiseSideOrientation;
  35141. }
  35142. else {
  35143. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35144. }
  35145. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35146. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35147. if (!doNotAdd) {
  35148. this._scene.materials.push(this);
  35149. }
  35150. }
  35151. Object.defineProperty(Material, "TriangleFillMode", {
  35152. /**
  35153. * Returns the triangle fill mode
  35154. */
  35155. get: function () {
  35156. return Material._TriangleFillMode;
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(Material, "WireFrameFillMode", {
  35162. /**
  35163. * Returns the wireframe mode
  35164. */
  35165. get: function () {
  35166. return Material._WireFrameFillMode;
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. Object.defineProperty(Material, "PointFillMode", {
  35172. /**
  35173. * Returns the point fill mode
  35174. */
  35175. get: function () {
  35176. return Material._PointFillMode;
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. Object.defineProperty(Material, "PointListDrawMode", {
  35182. /**
  35183. * Returns the point list draw mode
  35184. */
  35185. get: function () {
  35186. return Material._PointListDrawMode;
  35187. },
  35188. enumerable: true,
  35189. configurable: true
  35190. });
  35191. Object.defineProperty(Material, "LineListDrawMode", {
  35192. /**
  35193. * Returns the line list draw mode
  35194. */
  35195. get: function () {
  35196. return Material._LineListDrawMode;
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. Object.defineProperty(Material, "LineLoopDrawMode", {
  35202. /**
  35203. * Returns the line loop draw mode
  35204. */
  35205. get: function () {
  35206. return Material._LineLoopDrawMode;
  35207. },
  35208. enumerable: true,
  35209. configurable: true
  35210. });
  35211. Object.defineProperty(Material, "LineStripDrawMode", {
  35212. /**
  35213. * Returns the line strip draw mode
  35214. */
  35215. get: function () {
  35216. return Material._LineStripDrawMode;
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35222. /**
  35223. * Returns the triangle strip draw mode
  35224. */
  35225. get: function () {
  35226. return Material._TriangleStripDrawMode;
  35227. },
  35228. enumerable: true,
  35229. configurable: true
  35230. });
  35231. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35232. /**
  35233. * Returns the triangle fan draw mode
  35234. */
  35235. get: function () {
  35236. return Material._TriangleFanDrawMode;
  35237. },
  35238. enumerable: true,
  35239. configurable: true
  35240. });
  35241. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35242. /**
  35243. * Returns the clock-wise side orientation
  35244. */
  35245. get: function () {
  35246. return Material._ClockWiseSideOrientation;
  35247. },
  35248. enumerable: true,
  35249. configurable: true
  35250. });
  35251. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35252. /**
  35253. * Returns the counter clock-wise side orientation
  35254. */
  35255. get: function () {
  35256. return Material._CounterClockWiseSideOrientation;
  35257. },
  35258. enumerable: true,
  35259. configurable: true
  35260. });
  35261. Object.defineProperty(Material, "TextureDirtyFlag", {
  35262. /**
  35263. * Returns the dirty texture flag value
  35264. */
  35265. get: function () {
  35266. return Material._TextureDirtyFlag;
  35267. },
  35268. enumerable: true,
  35269. configurable: true
  35270. });
  35271. Object.defineProperty(Material, "LightDirtyFlag", {
  35272. /**
  35273. * Returns the dirty light flag value
  35274. */
  35275. get: function () {
  35276. return Material._LightDirtyFlag;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35282. /**
  35283. * Returns the dirty fresnel flag value
  35284. */
  35285. get: function () {
  35286. return Material._FresnelDirtyFlag;
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35292. /**
  35293. * Returns the dirty attributes flag value
  35294. */
  35295. get: function () {
  35296. return Material._AttributesDirtyFlag;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(Material, "MiscDirtyFlag", {
  35302. /**
  35303. * Returns the dirty misc flag value
  35304. */
  35305. get: function () {
  35306. return Material._MiscDirtyFlag;
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. Object.defineProperty(Material.prototype, "alpha", {
  35312. /**
  35313. * Gets the alpha value of the material
  35314. */
  35315. get: function () {
  35316. return this._alpha;
  35317. },
  35318. /**
  35319. * Sets the alpha value of the material
  35320. */
  35321. set: function (value) {
  35322. if (this._alpha === value) {
  35323. return;
  35324. }
  35325. this._alpha = value;
  35326. this.markAsDirty(Material.MiscDirtyFlag);
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35332. /**
  35333. * Gets the back-face culling state
  35334. */
  35335. get: function () {
  35336. return this._backFaceCulling;
  35337. },
  35338. /**
  35339. * Sets the back-face culling state
  35340. */
  35341. set: function (value) {
  35342. if (this._backFaceCulling === value) {
  35343. return;
  35344. }
  35345. this._backFaceCulling = value;
  35346. this.markAsDirty(Material.TextureDirtyFlag);
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. Object.defineProperty(Material.prototype, "onDispose", {
  35352. /**
  35353. * Called during a dispose event
  35354. */
  35355. set: function (callback) {
  35356. if (this._onDisposeObserver) {
  35357. this.onDisposeObservable.remove(this._onDisposeObserver);
  35358. }
  35359. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(Material.prototype, "onBind", {
  35365. /**
  35366. * Called during a bind event
  35367. */
  35368. set: function (callback) {
  35369. if (this._onBindObserver) {
  35370. this.onBindObservable.remove(this._onBindObserver);
  35371. }
  35372. this._onBindObserver = this.onBindObservable.add(callback);
  35373. },
  35374. enumerable: true,
  35375. configurable: true
  35376. });
  35377. Object.defineProperty(Material.prototype, "alphaMode", {
  35378. /**
  35379. * Gets the value of the alpha mode
  35380. */
  35381. get: function () {
  35382. return this._alphaMode;
  35383. },
  35384. /**
  35385. * Sets the value of the alpha mode.
  35386. *
  35387. * | Value | Type | Description |
  35388. * | --- | --- | --- |
  35389. * | 0 | ALPHA_DISABLE | |
  35390. * | 1 | ALPHA_ADD | |
  35391. * | 2 | ALPHA_COMBINE | |
  35392. * | 3 | ALPHA_SUBTRACT | |
  35393. * | 4 | ALPHA_MULTIPLY | |
  35394. * | 5 | ALPHA_MAXIMIZED | |
  35395. * | 6 | ALPHA_ONEONE | |
  35396. * | 7 | ALPHA_PREMULTIPLIED | |
  35397. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35398. * | 9 | ALPHA_INTERPOLATE | |
  35399. * | 10 | ALPHA_SCREENMODE | |
  35400. *
  35401. */
  35402. set: function (value) {
  35403. if (this._alphaMode === value) {
  35404. return;
  35405. }
  35406. this._alphaMode = value;
  35407. this.markAsDirty(Material.TextureDirtyFlag);
  35408. },
  35409. enumerable: true,
  35410. configurable: true
  35411. });
  35412. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35413. /**
  35414. * Gets the depth pre-pass value
  35415. */
  35416. get: function () {
  35417. return this._needDepthPrePass;
  35418. },
  35419. /**
  35420. * Sets the need depth pre-pass value
  35421. */
  35422. set: function (value) {
  35423. if (this._needDepthPrePass === value) {
  35424. return;
  35425. }
  35426. this._needDepthPrePass = value;
  35427. if (this._needDepthPrePass) {
  35428. this.checkReadyOnEveryCall = true;
  35429. }
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. Object.defineProperty(Material.prototype, "fogEnabled", {
  35435. /**
  35436. * Gets the value of the fog enabled state
  35437. */
  35438. get: function () {
  35439. return this._fogEnabled;
  35440. },
  35441. /**
  35442. * Sets the state for enabling fog
  35443. */
  35444. set: function (value) {
  35445. if (this._fogEnabled === value) {
  35446. return;
  35447. }
  35448. this._fogEnabled = value;
  35449. this.markAsDirty(Material.MiscDirtyFlag);
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(Material.prototype, "wireframe", {
  35455. /**
  35456. * Gets a value specifying if wireframe mode is enabled
  35457. */
  35458. get: function () {
  35459. switch (this._fillMode) {
  35460. case Material.WireFrameFillMode:
  35461. case Material.LineListDrawMode:
  35462. case Material.LineLoopDrawMode:
  35463. case Material.LineStripDrawMode:
  35464. return true;
  35465. }
  35466. return this._scene.forceWireframe;
  35467. },
  35468. /**
  35469. * Sets the state of wireframe mode
  35470. */
  35471. set: function (value) {
  35472. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35473. },
  35474. enumerable: true,
  35475. configurable: true
  35476. });
  35477. Object.defineProperty(Material.prototype, "pointsCloud", {
  35478. /**
  35479. * Gets the value specifying if point clouds are enabled
  35480. */
  35481. get: function () {
  35482. switch (this._fillMode) {
  35483. case Material.PointFillMode:
  35484. case Material.PointListDrawMode:
  35485. return true;
  35486. }
  35487. return this._scene.forcePointsCloud;
  35488. },
  35489. /**
  35490. * Sets the state of point cloud mode
  35491. */
  35492. set: function (value) {
  35493. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35494. },
  35495. enumerable: true,
  35496. configurable: true
  35497. });
  35498. Object.defineProperty(Material.prototype, "fillMode", {
  35499. /**
  35500. * Gets the material fill mode
  35501. */
  35502. get: function () {
  35503. return this._fillMode;
  35504. },
  35505. /**
  35506. * Sets the material fill mode
  35507. */
  35508. set: function (value) {
  35509. if (this._fillMode === value) {
  35510. return;
  35511. }
  35512. this._fillMode = value;
  35513. this.markAsDirty(Material.MiscDirtyFlag);
  35514. },
  35515. enumerable: true,
  35516. configurable: true
  35517. });
  35518. /**
  35519. * Returns a string representation of the current material
  35520. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35521. * @returns a string with material information
  35522. */
  35523. Material.prototype.toString = function (fullDetails) {
  35524. var ret = "Name: " + this.name;
  35525. if (fullDetails) {
  35526. }
  35527. return ret;
  35528. };
  35529. /**
  35530. * Gets the class name of the material
  35531. * @returns a string with the class name of the material
  35532. */
  35533. Material.prototype.getClassName = function () {
  35534. return "Material";
  35535. };
  35536. Object.defineProperty(Material.prototype, "isFrozen", {
  35537. /**
  35538. * Specifies if updates for the material been locked
  35539. */
  35540. get: function () {
  35541. return this.checkReadyOnlyOnce;
  35542. },
  35543. enumerable: true,
  35544. configurable: true
  35545. });
  35546. /**
  35547. * Locks updates for the material
  35548. */
  35549. Material.prototype.freeze = function () {
  35550. this.checkReadyOnlyOnce = true;
  35551. };
  35552. /**
  35553. * Unlocks updates for the material
  35554. */
  35555. Material.prototype.unfreeze = function () {
  35556. this.checkReadyOnlyOnce = false;
  35557. };
  35558. /**
  35559. * Specifies if the material is ready to be used
  35560. * @param mesh defines the mesh to check
  35561. * @param useInstances specifies if instances should be used
  35562. * @returns a boolean indicating if the material is ready to be used
  35563. */
  35564. Material.prototype.isReady = function (mesh, useInstances) {
  35565. return true;
  35566. };
  35567. /**
  35568. * Specifies that the submesh is ready to be used
  35569. * @param mesh defines the mesh to check
  35570. * @param subMesh defines which submesh to check
  35571. * @param useInstances specifies that instances should be used
  35572. * @returns a boolean indicating that the submesh is ready or not
  35573. */
  35574. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35575. return false;
  35576. };
  35577. /**
  35578. * Returns the material effect
  35579. * @returns the effect associated with the material
  35580. */
  35581. Material.prototype.getEffect = function () {
  35582. return this._effect;
  35583. };
  35584. /**
  35585. * Returns the current scene
  35586. * @returns a Scene
  35587. */
  35588. Material.prototype.getScene = function () {
  35589. return this._scene;
  35590. };
  35591. /**
  35592. * Specifies if the material will require alpha blending
  35593. * @returns a boolean specifying if alpha blending is needed
  35594. */
  35595. Material.prototype.needAlphaBlending = function () {
  35596. return (this.alpha < 1.0);
  35597. };
  35598. /**
  35599. * Specifies if the mesh will require alpha blending
  35600. * @param mesh defines the mesh to check
  35601. * @returns a boolean specifying if alpha blending is needed for the mesh
  35602. */
  35603. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35604. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35605. };
  35606. /**
  35607. * Specifies if this material should be rendered in alpha test mode
  35608. * @returns a boolean specifying if an alpha test is needed.
  35609. */
  35610. Material.prototype.needAlphaTesting = function () {
  35611. return false;
  35612. };
  35613. /**
  35614. * Gets the texture used for the alpha test
  35615. * @returns the texture to use for alpha testing
  35616. */
  35617. Material.prototype.getAlphaTestTexture = function () {
  35618. return null;
  35619. };
  35620. /**
  35621. * Marks the material to indicate that it needs to be re-calculated
  35622. */
  35623. Material.prototype.markDirty = function () {
  35624. this._wasPreviouslyReady = false;
  35625. };
  35626. /** @hidden */
  35627. Material.prototype._preBind = function (effect, overrideOrientation) {
  35628. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35629. var engine = this._scene.getEngine();
  35630. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35631. var reverse = orientation === Material.ClockWiseSideOrientation;
  35632. engine.enableEffect(effect ? effect : this._effect);
  35633. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35634. return reverse;
  35635. };
  35636. /**
  35637. * Binds the material to the mesh
  35638. * @param world defines the world transformation matrix
  35639. * @param mesh defines the mesh to bind the material to
  35640. */
  35641. Material.prototype.bind = function (world, mesh) {
  35642. };
  35643. /**
  35644. * Binds the submesh to the material
  35645. * @param world defines the world transformation matrix
  35646. * @param mesh defines the mesh containing the submesh
  35647. * @param subMesh defines the submesh to bind the material to
  35648. */
  35649. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35650. };
  35651. /**
  35652. * Binds the world matrix to the material
  35653. * @param world defines the world transformation matrix
  35654. */
  35655. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35656. };
  35657. /**
  35658. * Binds the scene's uniform buffer to the effect.
  35659. * @param effect defines the effect to bind to the scene uniform buffer
  35660. * @param sceneUbo defines the uniform buffer storing scene data
  35661. */
  35662. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35663. sceneUbo.bindToEffect(effect, "Scene");
  35664. };
  35665. /**
  35666. * Binds the view matrix to the effect
  35667. * @param effect defines the effect to bind the view matrix to
  35668. */
  35669. Material.prototype.bindView = function (effect) {
  35670. if (!this._useUBO) {
  35671. effect.setMatrix("view", this.getScene().getViewMatrix());
  35672. }
  35673. else {
  35674. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35675. }
  35676. };
  35677. /**
  35678. * Binds the view projection matrix to the effect
  35679. * @param effect defines the effect to bind the view projection matrix to
  35680. */
  35681. Material.prototype.bindViewProjection = function (effect) {
  35682. if (!this._useUBO) {
  35683. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35684. }
  35685. else {
  35686. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35687. }
  35688. };
  35689. /**
  35690. * Specifies if material alpha testing should be turned on for the mesh
  35691. * @param mesh defines the mesh to check
  35692. */
  35693. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35694. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35695. };
  35696. /**
  35697. * Processes to execute after binding the material to a mesh
  35698. * @param mesh defines the rendered mesh
  35699. */
  35700. Material.prototype._afterBind = function (mesh) {
  35701. this._scene._cachedMaterial = this;
  35702. if (mesh) {
  35703. this._scene._cachedVisibility = mesh.visibility;
  35704. }
  35705. else {
  35706. this._scene._cachedVisibility = 1;
  35707. }
  35708. if (mesh) {
  35709. this.onBindObservable.notifyObservers(mesh);
  35710. }
  35711. if (this.disableDepthWrite) {
  35712. var engine = this._scene.getEngine();
  35713. this._cachedDepthWriteState = engine.getDepthWrite();
  35714. engine.setDepthWrite(false);
  35715. }
  35716. };
  35717. /**
  35718. * Unbinds the material from the mesh
  35719. */
  35720. Material.prototype.unbind = function () {
  35721. this.onUnBindObservable.notifyObservers(this);
  35722. if (this.disableDepthWrite) {
  35723. var engine = this._scene.getEngine();
  35724. engine.setDepthWrite(this._cachedDepthWriteState);
  35725. }
  35726. };
  35727. /**
  35728. * Gets the active textures from the material
  35729. * @returns an array of textures
  35730. */
  35731. Material.prototype.getActiveTextures = function () {
  35732. return [];
  35733. };
  35734. /**
  35735. * Specifies if the material uses a texture
  35736. * @param texture defines the texture to check against the material
  35737. * @returns a boolean specifying if the material uses the texture
  35738. */
  35739. Material.prototype.hasTexture = function (texture) {
  35740. return false;
  35741. };
  35742. /**
  35743. * Makes a duplicate of the material, and gives it a new name
  35744. * @param name defines the new name for the duplicated material
  35745. * @returns the cloned material
  35746. */
  35747. Material.prototype.clone = function (name) {
  35748. return null;
  35749. };
  35750. /**
  35751. * Gets the meshes bound to the material
  35752. * @returns an array of meshes bound to the material
  35753. */
  35754. Material.prototype.getBindedMeshes = function () {
  35755. var result = new Array();
  35756. for (var index = 0; index < this._scene.meshes.length; index++) {
  35757. var mesh = this._scene.meshes[index];
  35758. if (mesh.material === this) {
  35759. result.push(mesh);
  35760. }
  35761. }
  35762. return result;
  35763. };
  35764. /**
  35765. * Force shader compilation
  35766. * @param mesh defines the mesh associated with this material
  35767. * @param onCompiled defines a function to execute once the material is compiled
  35768. * @param options defines the options to configure the compilation
  35769. */
  35770. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35771. var _this = this;
  35772. var localOptions = __assign({ clipPlane: false }, options);
  35773. var subMesh = new BABYLON.BaseSubMesh();
  35774. var scene = this.getScene();
  35775. var checkReady = function () {
  35776. if (!_this._scene || !_this._scene.getEngine()) {
  35777. return;
  35778. }
  35779. if (subMesh._materialDefines) {
  35780. subMesh._materialDefines._renderId = -1;
  35781. }
  35782. var clipPlaneState = scene.clipPlane;
  35783. if (localOptions.clipPlane) {
  35784. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35785. }
  35786. if (_this.storeEffectOnSubMeshes) {
  35787. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35788. if (onCompiled) {
  35789. onCompiled(_this);
  35790. }
  35791. }
  35792. else {
  35793. setTimeout(checkReady, 16);
  35794. }
  35795. }
  35796. else {
  35797. if (_this.isReady(mesh)) {
  35798. if (onCompiled) {
  35799. onCompiled(_this);
  35800. }
  35801. }
  35802. else {
  35803. setTimeout(checkReady, 16);
  35804. }
  35805. }
  35806. if (localOptions.clipPlane) {
  35807. scene.clipPlane = clipPlaneState;
  35808. }
  35809. };
  35810. checkReady();
  35811. };
  35812. /**
  35813. * Force shader compilation
  35814. * @param mesh defines the mesh that will use this material
  35815. * @param options defines additional options for compiling the shaders
  35816. * @returns a promise that resolves when the compilation completes
  35817. */
  35818. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35819. var _this = this;
  35820. return new Promise(function (resolve) {
  35821. _this.forceCompilation(mesh, function () {
  35822. resolve();
  35823. }, options);
  35824. });
  35825. };
  35826. /**
  35827. * Marks a define in the material to indicate that it needs to be re-computed
  35828. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35829. */
  35830. Material.prototype.markAsDirty = function (flag) {
  35831. if (flag & Material.TextureDirtyFlag) {
  35832. this._markAllSubMeshesAsTexturesDirty();
  35833. }
  35834. if (flag & Material.LightDirtyFlag) {
  35835. this._markAllSubMeshesAsLightsDirty();
  35836. }
  35837. if (flag & Material.FresnelDirtyFlag) {
  35838. this._markAllSubMeshesAsFresnelDirty();
  35839. }
  35840. if (flag & Material.AttributesDirtyFlag) {
  35841. this._markAllSubMeshesAsAttributesDirty();
  35842. }
  35843. if (flag & Material.MiscDirtyFlag) {
  35844. this._markAllSubMeshesAsMiscDirty();
  35845. }
  35846. this.getScene().resetCachedMaterial();
  35847. };
  35848. /**
  35849. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35850. * @param func defines a function which checks material defines against the submeshes
  35851. */
  35852. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35853. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35854. var mesh = _a[_i];
  35855. if (!mesh.subMeshes) {
  35856. continue;
  35857. }
  35858. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35859. var subMesh = _c[_b];
  35860. if (subMesh.getMaterial() !== this) {
  35861. continue;
  35862. }
  35863. if (!subMesh._materialDefines) {
  35864. continue;
  35865. }
  35866. func(subMesh._materialDefines);
  35867. }
  35868. }
  35869. };
  35870. /**
  35871. * Indicates that image processing needs to be re-calculated for all submeshes
  35872. */
  35873. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35874. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35875. };
  35876. /**
  35877. * Indicates that textures need to be re-calculated for all submeshes
  35878. */
  35879. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35880. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35881. };
  35882. /**
  35883. * Indicates that fresnel needs to be re-calculated for all submeshes
  35884. */
  35885. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35886. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35887. };
  35888. /**
  35889. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35890. */
  35891. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35892. this._markAllSubMeshesAsDirty(function (defines) {
  35893. defines.markAsFresnelDirty();
  35894. defines.markAsMiscDirty();
  35895. });
  35896. };
  35897. /**
  35898. * Indicates that lights need to be re-calculated for all submeshes
  35899. */
  35900. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35901. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35902. };
  35903. /**
  35904. * Indicates that attributes need to be re-calculated for all submeshes
  35905. */
  35906. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35907. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35908. };
  35909. /**
  35910. * Indicates that misc needs to be re-calculated for all submeshes
  35911. */
  35912. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35913. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35914. };
  35915. /**
  35916. * Indicates that textures and misc need to be re-calculated for all submeshes
  35917. */
  35918. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35919. this._markAllSubMeshesAsDirty(function (defines) {
  35920. defines.markAsTexturesDirty();
  35921. defines.markAsMiscDirty();
  35922. });
  35923. };
  35924. /**
  35925. * Disposes the material
  35926. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35927. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35928. */
  35929. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35930. // Animations
  35931. this.getScene().stopAnimation(this);
  35932. this.getScene().freeProcessedMaterials();
  35933. // Remove from scene
  35934. var index = this._scene.materials.indexOf(this);
  35935. if (index >= 0) {
  35936. this._scene.materials.splice(index, 1);
  35937. }
  35938. // Remove from meshes
  35939. for (index = 0; index < this._scene.meshes.length; index++) {
  35940. var mesh = this._scene.meshes[index];
  35941. if (mesh.material === this) {
  35942. mesh.material = null;
  35943. if (mesh.geometry) {
  35944. var geometry = (mesh.geometry);
  35945. if (this.storeEffectOnSubMeshes) {
  35946. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35947. var subMesh = _a[_i];
  35948. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35949. if (forceDisposeEffect && subMesh._materialEffect) {
  35950. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35951. }
  35952. }
  35953. }
  35954. else {
  35955. geometry._releaseVertexArrayObject(this._effect);
  35956. }
  35957. }
  35958. }
  35959. }
  35960. this._uniformBuffer.dispose();
  35961. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35962. if (forceDisposeEffect && this._effect) {
  35963. if (!this.storeEffectOnSubMeshes) {
  35964. this._scene.getEngine()._releaseEffect(this._effect);
  35965. }
  35966. this._effect = null;
  35967. }
  35968. // Callback
  35969. this.onDisposeObservable.notifyObservers(this);
  35970. this.onDisposeObservable.clear();
  35971. this.onBindObservable.clear();
  35972. this.onUnBindObservable.clear();
  35973. };
  35974. /**
  35975. * Serializes this material
  35976. * @returns the serialized material object
  35977. */
  35978. Material.prototype.serialize = function () {
  35979. return BABYLON.SerializationHelper.Serialize(this);
  35980. };
  35981. /**
  35982. * Creates a MultiMaterial from parsed MultiMaterial data.
  35983. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35984. * @param scene defines the hosting scene
  35985. * @returns a new MultiMaterial
  35986. */
  35987. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35988. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35989. multiMaterial.id = parsedMultiMaterial.id;
  35990. if (BABYLON.Tags) {
  35991. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35992. }
  35993. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35994. var subMatId = parsedMultiMaterial.materials[matIndex];
  35995. if (subMatId) {
  35996. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35997. }
  35998. else {
  35999. multiMaterial.subMaterials.push(null);
  36000. }
  36001. }
  36002. return multiMaterial;
  36003. };
  36004. /**
  36005. * Creates a material from parsed material data
  36006. * @param parsedMaterial defines parsed material data
  36007. * @param scene defines the hosting scene
  36008. * @param rootUrl defines the root URL to use to load textures
  36009. * @returns a new material
  36010. */
  36011. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36012. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36013. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36014. }
  36015. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36016. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36017. if (!BABYLON.LegacyPBRMaterial) {
  36018. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36019. return;
  36020. }
  36021. }
  36022. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36023. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36024. };
  36025. // Triangle views
  36026. Material._TriangleFillMode = 0;
  36027. Material._WireFrameFillMode = 1;
  36028. Material._PointFillMode = 2;
  36029. // Draw modes
  36030. Material._PointListDrawMode = 3;
  36031. Material._LineListDrawMode = 4;
  36032. Material._LineLoopDrawMode = 5;
  36033. Material._LineStripDrawMode = 6;
  36034. Material._TriangleStripDrawMode = 7;
  36035. Material._TriangleFanDrawMode = 8;
  36036. /**
  36037. * Stores the clock-wise side orientation
  36038. */
  36039. Material._ClockWiseSideOrientation = 0;
  36040. /**
  36041. * Stores the counter clock-wise side orientation
  36042. */
  36043. Material._CounterClockWiseSideOrientation = 1;
  36044. /**
  36045. * The dirty texture flag value
  36046. */
  36047. Material._TextureDirtyFlag = 1;
  36048. /**
  36049. * The dirty light flag value
  36050. */
  36051. Material._LightDirtyFlag = 2;
  36052. /**
  36053. * The dirty fresnel flag value
  36054. */
  36055. Material._FresnelDirtyFlag = 4;
  36056. /**
  36057. * The dirty attribute flag value
  36058. */
  36059. Material._AttributesDirtyFlag = 8;
  36060. /**
  36061. * The dirty misc flag value
  36062. */
  36063. Material._MiscDirtyFlag = 16;
  36064. __decorate([
  36065. BABYLON.serialize()
  36066. ], Material.prototype, "id", void 0);
  36067. __decorate([
  36068. BABYLON.serialize()
  36069. ], Material.prototype, "uniqueId", void 0);
  36070. __decorate([
  36071. BABYLON.serialize()
  36072. ], Material.prototype, "name", void 0);
  36073. __decorate([
  36074. BABYLON.serialize()
  36075. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36076. __decorate([
  36077. BABYLON.serialize()
  36078. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36079. __decorate([
  36080. BABYLON.serialize()
  36081. ], Material.prototype, "state", void 0);
  36082. __decorate([
  36083. BABYLON.serialize("alpha")
  36084. ], Material.prototype, "_alpha", void 0);
  36085. __decorate([
  36086. BABYLON.serialize("backFaceCulling")
  36087. ], Material.prototype, "_backFaceCulling", void 0);
  36088. __decorate([
  36089. BABYLON.serialize()
  36090. ], Material.prototype, "sideOrientation", void 0);
  36091. __decorate([
  36092. BABYLON.serialize("alphaMode")
  36093. ], Material.prototype, "_alphaMode", void 0);
  36094. __decorate([
  36095. BABYLON.serialize()
  36096. ], Material.prototype, "_needDepthPrePass", void 0);
  36097. __decorate([
  36098. BABYLON.serialize()
  36099. ], Material.prototype, "disableDepthWrite", void 0);
  36100. __decorate([
  36101. BABYLON.serialize()
  36102. ], Material.prototype, "forceDepthWrite", void 0);
  36103. __decorate([
  36104. BABYLON.serialize()
  36105. ], Material.prototype, "separateCullingPass", void 0);
  36106. __decorate([
  36107. BABYLON.serialize("fogEnabled")
  36108. ], Material.prototype, "_fogEnabled", void 0);
  36109. __decorate([
  36110. BABYLON.serialize()
  36111. ], Material.prototype, "pointSize", void 0);
  36112. __decorate([
  36113. BABYLON.serialize()
  36114. ], Material.prototype, "zOffset", void 0);
  36115. __decorate([
  36116. BABYLON.serialize()
  36117. ], Material.prototype, "wireframe", null);
  36118. __decorate([
  36119. BABYLON.serialize()
  36120. ], Material.prototype, "pointsCloud", null);
  36121. __decorate([
  36122. BABYLON.serialize()
  36123. ], Material.prototype, "fillMode", null);
  36124. return Material;
  36125. }());
  36126. BABYLON.Material = Material;
  36127. })(BABYLON || (BABYLON = {}));
  36128. //# sourceMappingURL=babylon.material.js.map
  36129. var BABYLON;
  36130. (function (BABYLON) {
  36131. var UniformBuffer = /** @class */ (function () {
  36132. /**
  36133. * Uniform buffer objects.
  36134. *
  36135. * Handles blocks of uniform on the GPU.
  36136. *
  36137. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36138. *
  36139. * For more information, please refer to :
  36140. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36141. */
  36142. function UniformBuffer(engine, data, dynamic) {
  36143. this._engine = engine;
  36144. this._noUBO = !engine.supportsUniformBuffers;
  36145. this._dynamic = dynamic;
  36146. this._data = data || [];
  36147. this._uniformLocations = {};
  36148. this._uniformSizes = {};
  36149. this._uniformLocationPointer = 0;
  36150. this._needSync = false;
  36151. if (this._noUBO) {
  36152. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36153. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36154. this.updateFloat = this._updateFloatForEffect;
  36155. this.updateFloat2 = this._updateFloat2ForEffect;
  36156. this.updateFloat3 = this._updateFloat3ForEffect;
  36157. this.updateFloat4 = this._updateFloat4ForEffect;
  36158. this.updateMatrix = this._updateMatrixForEffect;
  36159. this.updateVector3 = this._updateVector3ForEffect;
  36160. this.updateVector4 = this._updateVector4ForEffect;
  36161. this.updateColor3 = this._updateColor3ForEffect;
  36162. this.updateColor4 = this._updateColor4ForEffect;
  36163. }
  36164. else {
  36165. this._engine._uniformBuffers.push(this);
  36166. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36167. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36168. this.updateFloat = this._updateFloatForUniform;
  36169. this.updateFloat2 = this._updateFloat2ForUniform;
  36170. this.updateFloat3 = this._updateFloat3ForUniform;
  36171. this.updateFloat4 = this._updateFloat4ForUniform;
  36172. this.updateMatrix = this._updateMatrixForUniform;
  36173. this.updateVector3 = this._updateVector3ForUniform;
  36174. this.updateVector4 = this._updateVector4ForUniform;
  36175. this.updateColor3 = this._updateColor3ForUniform;
  36176. this.updateColor4 = this._updateColor4ForUniform;
  36177. }
  36178. }
  36179. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36180. // Properties
  36181. /**
  36182. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36183. * or just falling back on setUniformXXX calls.
  36184. */
  36185. get: function () {
  36186. return !this._noUBO;
  36187. },
  36188. enumerable: true,
  36189. configurable: true
  36190. });
  36191. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36192. /**
  36193. * Indicates if the WebGL underlying uniform buffer is in sync
  36194. * with the javascript cache data.
  36195. */
  36196. get: function () {
  36197. return !this._needSync;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. /**
  36203. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36204. * Also, a dynamic UniformBuffer will disable cache verification and always
  36205. * update the underlying WebGL uniform buffer to the GPU.
  36206. */
  36207. UniformBuffer.prototype.isDynamic = function () {
  36208. return this._dynamic !== undefined;
  36209. };
  36210. /**
  36211. * The data cache on JS side.
  36212. */
  36213. UniformBuffer.prototype.getData = function () {
  36214. return this._bufferData;
  36215. };
  36216. /**
  36217. * The underlying WebGL Uniform buffer.
  36218. */
  36219. UniformBuffer.prototype.getBuffer = function () {
  36220. return this._buffer;
  36221. };
  36222. /**
  36223. * std140 layout specifies how to align data within an UBO structure.
  36224. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36225. * for specs.
  36226. */
  36227. UniformBuffer.prototype._fillAlignment = function (size) {
  36228. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36229. // and 4x4 matrices
  36230. // TODO : change if other types are used
  36231. var alignment;
  36232. if (size <= 2) {
  36233. alignment = size;
  36234. }
  36235. else {
  36236. alignment = 4;
  36237. }
  36238. if ((this._uniformLocationPointer % alignment) !== 0) {
  36239. var oldPointer = this._uniformLocationPointer;
  36240. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36241. var diff = this._uniformLocationPointer - oldPointer;
  36242. for (var i = 0; i < diff; i++) {
  36243. this._data.push(0);
  36244. }
  36245. }
  36246. };
  36247. /**
  36248. * Adds an uniform in the buffer.
  36249. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36250. * for the layout to be correct !
  36251. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36252. * @param {number|number[]} size Data size, or data directly.
  36253. */
  36254. UniformBuffer.prototype.addUniform = function (name, size) {
  36255. if (this._noUBO) {
  36256. return;
  36257. }
  36258. if (this._uniformLocations[name] !== undefined) {
  36259. // Already existing uniform
  36260. return;
  36261. }
  36262. // This function must be called in the order of the shader layout !
  36263. // size can be the size of the uniform, or data directly
  36264. var data;
  36265. if (size instanceof Array) {
  36266. data = size;
  36267. size = data.length;
  36268. }
  36269. else {
  36270. size = size;
  36271. data = [];
  36272. // Fill with zeros
  36273. for (var i = 0; i < size; i++) {
  36274. data.push(0);
  36275. }
  36276. }
  36277. this._fillAlignment(size);
  36278. this._uniformSizes[name] = size;
  36279. this._uniformLocations[name] = this._uniformLocationPointer;
  36280. this._uniformLocationPointer += size;
  36281. for (var i = 0; i < size; i++) {
  36282. this._data.push(data[i]);
  36283. }
  36284. this._needSync = true;
  36285. };
  36286. /**
  36287. * Wrapper for addUniform.
  36288. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36289. * @param {Matrix} mat A 4x4 matrix.
  36290. */
  36291. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36292. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36293. };
  36294. /**
  36295. * Wrapper for addUniform.
  36296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36297. * @param {number} x
  36298. * @param {number} y
  36299. */
  36300. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36301. var temp = [x, y];
  36302. this.addUniform(name, temp);
  36303. };
  36304. /**
  36305. * Wrapper for addUniform.
  36306. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36307. * @param {number} x
  36308. * @param {number} y
  36309. * @param {number} z
  36310. */
  36311. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36312. var temp = [x, y, z];
  36313. this.addUniform(name, temp);
  36314. };
  36315. /**
  36316. * Wrapper for addUniform.
  36317. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36318. * @param {Color3} color
  36319. */
  36320. UniformBuffer.prototype.addColor3 = function (name, color) {
  36321. var temp = new Array();
  36322. color.toArray(temp);
  36323. this.addUniform(name, temp);
  36324. };
  36325. /**
  36326. * Wrapper for addUniform.
  36327. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36328. * @param {Color3} color
  36329. * @param {number} alpha
  36330. */
  36331. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36332. var temp = new Array();
  36333. color.toArray(temp);
  36334. temp.push(alpha);
  36335. this.addUniform(name, temp);
  36336. };
  36337. /**
  36338. * Wrapper for addUniform.
  36339. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36340. * @param {Vector3} vector
  36341. */
  36342. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36343. var temp = new Array();
  36344. vector.toArray(temp);
  36345. this.addUniform(name, temp);
  36346. };
  36347. /**
  36348. * Wrapper for addUniform.
  36349. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36350. */
  36351. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36352. this.addUniform(name, 12);
  36353. };
  36354. /**
  36355. * Wrapper for addUniform.
  36356. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36357. */
  36358. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36359. this.addUniform(name, 8);
  36360. };
  36361. /**
  36362. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36363. */
  36364. UniformBuffer.prototype.create = function () {
  36365. if (this._noUBO) {
  36366. return;
  36367. }
  36368. if (this._buffer) {
  36369. return; // nothing to do
  36370. }
  36371. // See spec, alignment must be filled as a vec4
  36372. this._fillAlignment(4);
  36373. this._bufferData = new Float32Array(this._data);
  36374. this._rebuild();
  36375. this._needSync = true;
  36376. };
  36377. UniformBuffer.prototype._rebuild = function () {
  36378. if (this._noUBO) {
  36379. return;
  36380. }
  36381. if (this._dynamic) {
  36382. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36383. }
  36384. else {
  36385. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36386. }
  36387. };
  36388. /**
  36389. * Updates the WebGL Uniform Buffer on the GPU.
  36390. * If the `dynamic` flag is set to true, no cache comparison is done.
  36391. * Otherwise, the buffer will be updated only if the cache differs.
  36392. */
  36393. UniformBuffer.prototype.update = function () {
  36394. if (!this._buffer) {
  36395. this.create();
  36396. return;
  36397. }
  36398. if (!this._dynamic && !this._needSync) {
  36399. return;
  36400. }
  36401. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36402. this._needSync = false;
  36403. };
  36404. /**
  36405. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36406. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36407. * @param {number[]|Float32Array} data Flattened data
  36408. * @param {number} size Size of the data.
  36409. */
  36410. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36411. var location = this._uniformLocations[uniformName];
  36412. if (location === undefined) {
  36413. if (this._buffer) {
  36414. // Cannot add an uniform if the buffer is already created
  36415. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36416. return;
  36417. }
  36418. this.addUniform(uniformName, size);
  36419. location = this._uniformLocations[uniformName];
  36420. }
  36421. if (!this._buffer) {
  36422. this.create();
  36423. }
  36424. if (!this._dynamic) {
  36425. // Cache for static uniform buffers
  36426. var changed = false;
  36427. for (var i = 0; i < size; i++) {
  36428. if (this._bufferData[location + i] !== data[i]) {
  36429. changed = true;
  36430. this._bufferData[location + i] = data[i];
  36431. }
  36432. }
  36433. this._needSync = this._needSync || changed;
  36434. }
  36435. else {
  36436. // No cache for dynamic
  36437. for (var i = 0; i < size; i++) {
  36438. this._bufferData[location + i] = data[i];
  36439. }
  36440. }
  36441. };
  36442. // Update methods
  36443. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36444. // To match std140, matrix must be realigned
  36445. for (var i = 0; i < 3; i++) {
  36446. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36447. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36448. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36449. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36450. }
  36451. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36452. };
  36453. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36454. this._currentEffect.setMatrix3x3(name, matrix);
  36455. };
  36456. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36457. this._currentEffect.setMatrix2x2(name, matrix);
  36458. };
  36459. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36460. // To match std140, matrix must be realigned
  36461. for (var i = 0; i < 2; i++) {
  36462. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36463. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36464. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36465. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36466. }
  36467. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36468. };
  36469. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36470. this._currentEffect.setFloat(name, x);
  36471. };
  36472. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36473. UniformBuffer._tempBuffer[0] = x;
  36474. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36475. };
  36476. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36477. if (suffix === void 0) { suffix = ""; }
  36478. this._currentEffect.setFloat2(name + suffix, x, y);
  36479. };
  36480. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36481. if (suffix === void 0) { suffix = ""; }
  36482. UniformBuffer._tempBuffer[0] = x;
  36483. UniformBuffer._tempBuffer[1] = y;
  36484. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36485. };
  36486. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36487. if (suffix === void 0) { suffix = ""; }
  36488. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36489. };
  36490. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36491. if (suffix === void 0) { suffix = ""; }
  36492. UniformBuffer._tempBuffer[0] = x;
  36493. UniformBuffer._tempBuffer[1] = y;
  36494. UniformBuffer._tempBuffer[2] = z;
  36495. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36496. };
  36497. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36498. if (suffix === void 0) { suffix = ""; }
  36499. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36500. };
  36501. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36502. if (suffix === void 0) { suffix = ""; }
  36503. UniformBuffer._tempBuffer[0] = x;
  36504. UniformBuffer._tempBuffer[1] = y;
  36505. UniformBuffer._tempBuffer[2] = z;
  36506. UniformBuffer._tempBuffer[3] = w;
  36507. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36508. };
  36509. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36510. this._currentEffect.setMatrix(name, mat);
  36511. };
  36512. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36513. this.updateUniform(name, mat.toArray(), 16);
  36514. };
  36515. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36516. this._currentEffect.setVector3(name, vector);
  36517. };
  36518. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36519. vector.toArray(UniformBuffer._tempBuffer);
  36520. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36521. };
  36522. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36523. this._currentEffect.setVector4(name, vector);
  36524. };
  36525. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36526. vector.toArray(UniformBuffer._tempBuffer);
  36527. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36528. };
  36529. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36530. if (suffix === void 0) { suffix = ""; }
  36531. this._currentEffect.setColor3(name + suffix, color);
  36532. };
  36533. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36534. if (suffix === void 0) { suffix = ""; }
  36535. color.toArray(UniformBuffer._tempBuffer);
  36536. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36537. };
  36538. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36539. if (suffix === void 0) { suffix = ""; }
  36540. this._currentEffect.setColor4(name + suffix, color, alpha);
  36541. };
  36542. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36543. if (suffix === void 0) { suffix = ""; }
  36544. color.toArray(UniformBuffer._tempBuffer);
  36545. UniformBuffer._tempBuffer[3] = alpha;
  36546. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36547. };
  36548. /**
  36549. * Sets a sampler uniform on the effect.
  36550. * @param {string} name Name of the sampler.
  36551. * @param {Texture} texture
  36552. */
  36553. UniformBuffer.prototype.setTexture = function (name, texture) {
  36554. this._currentEffect.setTexture(name, texture);
  36555. };
  36556. /**
  36557. * Directly updates the value of the uniform in the cache AND on the GPU.
  36558. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36559. * @param {number[]|Float32Array} data Flattened data
  36560. */
  36561. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36562. this.updateUniform(uniformName, data, data.length);
  36563. this.update();
  36564. };
  36565. /**
  36566. * Binds this uniform buffer to an effect.
  36567. * @param {Effect} effect
  36568. * @param {string} name Name of the uniform block in the shader.
  36569. */
  36570. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36571. this._currentEffect = effect;
  36572. if (this._noUBO || !this._buffer) {
  36573. return;
  36574. }
  36575. effect.bindUniformBuffer(this._buffer, name);
  36576. };
  36577. /**
  36578. * Disposes the uniform buffer.
  36579. */
  36580. UniformBuffer.prototype.dispose = function () {
  36581. if (this._noUBO) {
  36582. return;
  36583. }
  36584. var index = this._engine._uniformBuffers.indexOf(this);
  36585. if (index !== -1) {
  36586. this._engine._uniformBuffers.splice(index, 1);
  36587. }
  36588. if (!this._buffer) {
  36589. return;
  36590. }
  36591. if (this._engine._releaseBuffer(this._buffer)) {
  36592. this._buffer = null;
  36593. }
  36594. };
  36595. // Pool for avoiding memory leaks
  36596. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36597. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36598. return UniformBuffer;
  36599. }());
  36600. BABYLON.UniformBuffer = UniformBuffer;
  36601. })(BABYLON || (BABYLON = {}));
  36602. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36603. var BABYLON;
  36604. (function (BABYLON) {
  36605. /**
  36606. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36607. */
  36608. var VertexData = /** @class */ (function () {
  36609. function VertexData() {
  36610. }
  36611. /**
  36612. * Uses the passed data array to set the set the values for the specified kind of data
  36613. * @param data a linear array of floating numbers
  36614. * @param kind the type of data that is being set, eg positions, colors etc
  36615. */
  36616. VertexData.prototype.set = function (data, kind) {
  36617. switch (kind) {
  36618. case BABYLON.VertexBuffer.PositionKind:
  36619. this.positions = data;
  36620. break;
  36621. case BABYLON.VertexBuffer.NormalKind:
  36622. this.normals = data;
  36623. break;
  36624. case BABYLON.VertexBuffer.TangentKind:
  36625. this.tangents = data;
  36626. break;
  36627. case BABYLON.VertexBuffer.UVKind:
  36628. this.uvs = data;
  36629. break;
  36630. case BABYLON.VertexBuffer.UV2Kind:
  36631. this.uvs2 = data;
  36632. break;
  36633. case BABYLON.VertexBuffer.UV3Kind:
  36634. this.uvs3 = data;
  36635. break;
  36636. case BABYLON.VertexBuffer.UV4Kind:
  36637. this.uvs4 = data;
  36638. break;
  36639. case BABYLON.VertexBuffer.UV5Kind:
  36640. this.uvs5 = data;
  36641. break;
  36642. case BABYLON.VertexBuffer.UV6Kind:
  36643. this.uvs6 = data;
  36644. break;
  36645. case BABYLON.VertexBuffer.ColorKind:
  36646. this.colors = data;
  36647. break;
  36648. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36649. this.matricesIndices = data;
  36650. break;
  36651. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36652. this.matricesWeights = data;
  36653. break;
  36654. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36655. this.matricesIndicesExtra = data;
  36656. break;
  36657. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36658. this.matricesWeightsExtra = data;
  36659. break;
  36660. }
  36661. };
  36662. /**
  36663. * Associates the vertexData to the passed Mesh.
  36664. * Sets it as updatable or not (default `false`)
  36665. * @param mesh the mesh the vertexData is applied to
  36666. * @param updatable when used and having the value true allows new data to update the vertexData
  36667. * @returns the VertexData
  36668. */
  36669. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36670. this._applyTo(mesh, updatable);
  36671. return this;
  36672. };
  36673. /**
  36674. * Associates the vertexData to the passed Geometry.
  36675. * Sets it as updatable or not (default `false`)
  36676. * @param geometry the geometry the vertexData is applied to
  36677. * @param updatable when used and having the value true allows new data to update the vertexData
  36678. * @returns VertexData
  36679. */
  36680. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36681. this._applyTo(geometry, updatable);
  36682. return this;
  36683. };
  36684. /**
  36685. * Updates the associated mesh
  36686. * @param mesh the mesh to be updated
  36687. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36688. * @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
  36689. * @returns VertexData
  36690. */
  36691. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36692. this._update(mesh);
  36693. return this;
  36694. };
  36695. /**
  36696. * Updates the associated geometry
  36697. * @param geometry the geometry to be updated
  36698. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36699. * @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
  36700. * @returns VertexData.
  36701. */
  36702. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36703. this._update(geometry);
  36704. return this;
  36705. };
  36706. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36707. if (updatable === void 0) { updatable = false; }
  36708. if (this.positions) {
  36709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36710. }
  36711. if (this.normals) {
  36712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36713. }
  36714. if (this.tangents) {
  36715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36716. }
  36717. if (this.uvs) {
  36718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36719. }
  36720. if (this.uvs2) {
  36721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36722. }
  36723. if (this.uvs3) {
  36724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36725. }
  36726. if (this.uvs4) {
  36727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36728. }
  36729. if (this.uvs5) {
  36730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36731. }
  36732. if (this.uvs6) {
  36733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36734. }
  36735. if (this.colors) {
  36736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36737. }
  36738. if (this.matricesIndices) {
  36739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36740. }
  36741. if (this.matricesWeights) {
  36742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36743. }
  36744. if (this.matricesIndicesExtra) {
  36745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36746. }
  36747. if (this.matricesWeightsExtra) {
  36748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36749. }
  36750. if (this.indices) {
  36751. meshOrGeometry.setIndices(this.indices, null, updatable);
  36752. }
  36753. else {
  36754. meshOrGeometry.setIndices([], null);
  36755. }
  36756. return this;
  36757. };
  36758. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36759. if (this.positions) {
  36760. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36761. }
  36762. if (this.normals) {
  36763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36764. }
  36765. if (this.tangents) {
  36766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36767. }
  36768. if (this.uvs) {
  36769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36770. }
  36771. if (this.uvs2) {
  36772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36773. }
  36774. if (this.uvs3) {
  36775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36776. }
  36777. if (this.uvs4) {
  36778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36779. }
  36780. if (this.uvs5) {
  36781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36782. }
  36783. if (this.uvs6) {
  36784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36785. }
  36786. if (this.colors) {
  36787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36788. }
  36789. if (this.matricesIndices) {
  36790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36791. }
  36792. if (this.matricesWeights) {
  36793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36794. }
  36795. if (this.matricesIndicesExtra) {
  36796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36797. }
  36798. if (this.matricesWeightsExtra) {
  36799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36800. }
  36801. if (this.indices) {
  36802. meshOrGeometry.setIndices(this.indices, null);
  36803. }
  36804. return this;
  36805. };
  36806. /**
  36807. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36808. * @param matrix the transforming matrix
  36809. * @returns the VertexData
  36810. */
  36811. VertexData.prototype.transform = function (matrix) {
  36812. var transformed = BABYLON.Vector3.Zero();
  36813. var index;
  36814. if (this.positions) {
  36815. var position = BABYLON.Vector3.Zero();
  36816. for (index = 0; index < this.positions.length; index += 3) {
  36817. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36818. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36819. this.positions[index] = transformed.x;
  36820. this.positions[index + 1] = transformed.y;
  36821. this.positions[index + 2] = transformed.z;
  36822. }
  36823. }
  36824. if (this.normals) {
  36825. var normal = BABYLON.Vector3.Zero();
  36826. for (index = 0; index < this.normals.length; index += 3) {
  36827. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36828. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36829. this.normals[index] = transformed.x;
  36830. this.normals[index + 1] = transformed.y;
  36831. this.normals[index + 2] = transformed.z;
  36832. }
  36833. }
  36834. if (this.tangents) {
  36835. var tangent = BABYLON.Vector4.Zero();
  36836. var tangentTransformed = BABYLON.Vector4.Zero();
  36837. for (index = 0; index < this.tangents.length; index += 4) {
  36838. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36839. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36840. this.tangents[index] = tangentTransformed.x;
  36841. this.tangents[index + 1] = tangentTransformed.y;
  36842. this.tangents[index + 2] = tangentTransformed.z;
  36843. this.tangents[index + 3] = tangentTransformed.w;
  36844. }
  36845. }
  36846. return this;
  36847. };
  36848. /**
  36849. * Merges the passed VertexData into the current one
  36850. * @param other the VertexData to be merged into the current one
  36851. * @returns the modified VertexData
  36852. */
  36853. VertexData.prototype.merge = function (other) {
  36854. this._validate();
  36855. other._validate();
  36856. if (!this.normals !== !other.normals ||
  36857. !this.tangents !== !other.tangents ||
  36858. !this.uvs !== !other.uvs ||
  36859. !this.uvs2 !== !other.uvs2 ||
  36860. !this.uvs3 !== !other.uvs3 ||
  36861. !this.uvs4 !== !other.uvs4 ||
  36862. !this.uvs5 !== !other.uvs5 ||
  36863. !this.uvs6 !== !other.uvs6 ||
  36864. !this.colors !== !other.colors ||
  36865. !this.matricesIndices !== !other.matricesIndices ||
  36866. !this.matricesWeights !== !other.matricesWeights ||
  36867. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36868. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36869. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36870. }
  36871. if (other.indices) {
  36872. if (!this.indices) {
  36873. this.indices = [];
  36874. }
  36875. var offset = this.positions ? this.positions.length / 3 : 0;
  36876. for (var index = 0; index < other.indices.length; index++) {
  36877. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36878. this.indices.push(other.indices[index] + offset);
  36879. }
  36880. }
  36881. this.positions = this._mergeElement(this.positions, other.positions);
  36882. this.normals = this._mergeElement(this.normals, other.normals);
  36883. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36884. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36885. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36886. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36887. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36888. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36889. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36890. this.colors = this._mergeElement(this.colors, other.colors);
  36891. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36892. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36893. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36894. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36895. return this;
  36896. };
  36897. VertexData.prototype._mergeElement = function (source, other) {
  36898. if (!source) {
  36899. return other;
  36900. }
  36901. if (!other) {
  36902. return source;
  36903. }
  36904. var len = other.length + source.length;
  36905. var isSrcTypedArray = source instanceof Float32Array;
  36906. var isOthTypedArray = other instanceof Float32Array;
  36907. // use non-loop method when the source is Float32Array
  36908. if (isSrcTypedArray) {
  36909. var ret32 = new Float32Array(len);
  36910. ret32.set(source);
  36911. ret32.set(other, source.length);
  36912. return ret32;
  36913. // source is number[], when other is also use concat
  36914. }
  36915. else if (!isOthTypedArray) {
  36916. return source.concat(other);
  36917. // source is a number[], but other is a Float32Array, loop required
  36918. }
  36919. else {
  36920. var ret = source.slice(0); // copy source to a separate array
  36921. for (var i = 0, len = other.length; i < len; i++) {
  36922. ret.push(other[i]);
  36923. }
  36924. return ret;
  36925. }
  36926. };
  36927. VertexData.prototype._validate = function () {
  36928. if (!this.positions) {
  36929. throw new Error("Positions are required");
  36930. }
  36931. var getElementCount = function (kind, values) {
  36932. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36933. if ((values.length % stride) !== 0) {
  36934. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36935. }
  36936. return values.length / stride;
  36937. };
  36938. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36939. var validateElementCount = function (kind, values) {
  36940. var elementCount = getElementCount(kind, values);
  36941. if (elementCount !== positionsElementCount) {
  36942. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36943. }
  36944. };
  36945. if (this.normals)
  36946. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36947. if (this.tangents)
  36948. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36949. if (this.uvs)
  36950. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36951. if (this.uvs2)
  36952. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36953. if (this.uvs3)
  36954. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36955. if (this.uvs4)
  36956. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36957. if (this.uvs5)
  36958. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36959. if (this.uvs6)
  36960. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36961. if (this.colors)
  36962. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36963. if (this.matricesIndices)
  36964. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36965. if (this.matricesWeights)
  36966. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36967. if (this.matricesIndicesExtra)
  36968. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36969. if (this.matricesWeightsExtra)
  36970. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36971. };
  36972. /**
  36973. * Serializes the VertexData
  36974. * @returns a serialized object
  36975. */
  36976. VertexData.prototype.serialize = function () {
  36977. var serializationObject = this.serialize();
  36978. if (this.positions) {
  36979. serializationObject.positions = this.positions;
  36980. }
  36981. if (this.normals) {
  36982. serializationObject.normals = this.normals;
  36983. }
  36984. if (this.tangents) {
  36985. serializationObject.tangents = this.tangents;
  36986. }
  36987. if (this.uvs) {
  36988. serializationObject.uvs = this.uvs;
  36989. }
  36990. if (this.uvs2) {
  36991. serializationObject.uvs2 = this.uvs2;
  36992. }
  36993. if (this.uvs3) {
  36994. serializationObject.uvs3 = this.uvs3;
  36995. }
  36996. if (this.uvs4) {
  36997. serializationObject.uvs4 = this.uvs4;
  36998. }
  36999. if (this.uvs5) {
  37000. serializationObject.uvs5 = this.uvs5;
  37001. }
  37002. if (this.uvs6) {
  37003. serializationObject.uvs6 = this.uvs6;
  37004. }
  37005. if (this.colors) {
  37006. serializationObject.colors = this.colors;
  37007. }
  37008. if (this.matricesIndices) {
  37009. serializationObject.matricesIndices = this.matricesIndices;
  37010. serializationObject.matricesIndices._isExpanded = true;
  37011. }
  37012. if (this.matricesWeights) {
  37013. serializationObject.matricesWeights = this.matricesWeights;
  37014. }
  37015. if (this.matricesIndicesExtra) {
  37016. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37017. serializationObject.matricesIndicesExtra._isExpanded = true;
  37018. }
  37019. if (this.matricesWeightsExtra) {
  37020. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37021. }
  37022. serializationObject.indices = this.indices;
  37023. return serializationObject;
  37024. };
  37025. // Statics
  37026. /**
  37027. * Extracts the vertexData from a mesh
  37028. * @param mesh the mesh from which to extract the VertexData
  37029. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37030. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37031. * @returns the object VertexData associated to the passed mesh
  37032. */
  37033. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37034. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37035. };
  37036. /**
  37037. * Extracts the vertexData from the geometry
  37038. * @param geometry the geometry from which to extract the VertexData
  37039. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37040. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37041. * @returns the object VertexData associated to the passed mesh
  37042. */
  37043. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37044. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37045. };
  37046. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37047. var result = new VertexData();
  37048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37049. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37050. }
  37051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37052. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37053. }
  37054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37055. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37056. }
  37057. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37058. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37059. }
  37060. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37061. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37062. }
  37063. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37064. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37065. }
  37066. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37067. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37068. }
  37069. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37070. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37071. }
  37072. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37073. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37074. }
  37075. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37076. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37077. }
  37078. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37079. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37080. }
  37081. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37082. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37083. }
  37084. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37085. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37086. }
  37087. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37088. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37089. }
  37090. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37091. return result;
  37092. };
  37093. /**
  37094. * Creates the VertexData for a Ribbon
  37095. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37096. * * pathArray array of paths, each of which an array of successive Vector3
  37097. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37098. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37099. * * 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
  37100. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37101. * * 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)
  37102. * * 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)
  37103. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37104. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37105. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37106. * @returns the VertexData of the ribbon
  37107. */
  37108. VertexData.CreateRibbon = function (options) {
  37109. var pathArray = options.pathArray;
  37110. var closeArray = options.closeArray || false;
  37111. var closePath = options.closePath || false;
  37112. var invertUV = options.invertUV || false;
  37113. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37114. var offset = options.offset || defaultOffset;
  37115. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37117. var customUV = options.uvs;
  37118. var customColors = options.colors;
  37119. var positions = [];
  37120. var indices = [];
  37121. var normals = [];
  37122. var uvs = [];
  37123. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37124. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37125. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37126. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37127. var minlg; // minimal length among all paths from pathArray
  37128. var lg = []; // array of path lengths : nb of vertex per path
  37129. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37130. var p; // path iterator
  37131. var i; // point iterator
  37132. var j; // point iterator
  37133. // if single path in pathArray
  37134. if (pathArray.length < 2) {
  37135. var ar1 = [];
  37136. var ar2 = [];
  37137. for (i = 0; i < pathArray[0].length - offset; i++) {
  37138. ar1.push(pathArray[0][i]);
  37139. ar2.push(pathArray[0][i + offset]);
  37140. }
  37141. pathArray = [ar1, ar2];
  37142. }
  37143. // positions and horizontal distances (u)
  37144. var idc = 0;
  37145. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37146. var path;
  37147. var l;
  37148. minlg = pathArray[0].length;
  37149. var vectlg;
  37150. var dist;
  37151. for (p = 0; p < pathArray.length; p++) {
  37152. uTotalDistance[p] = 0;
  37153. us[p] = [0];
  37154. path = pathArray[p];
  37155. l = path.length;
  37156. minlg = (minlg < l) ? minlg : l;
  37157. j = 0;
  37158. while (j < l) {
  37159. positions.push(path[j].x, path[j].y, path[j].z);
  37160. if (j > 0) {
  37161. vectlg = path[j].subtract(path[j - 1]).length();
  37162. dist = vectlg + uTotalDistance[p];
  37163. us[p].push(dist);
  37164. uTotalDistance[p] = dist;
  37165. }
  37166. j++;
  37167. }
  37168. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37169. j--;
  37170. positions.push(path[0].x, path[0].y, path[0].z);
  37171. vectlg = path[j].subtract(path[0]).length();
  37172. dist = vectlg + uTotalDistance[p];
  37173. us[p].push(dist);
  37174. uTotalDistance[p] = dist;
  37175. }
  37176. lg[p] = l + closePathCorr;
  37177. idx[p] = idc;
  37178. idc += (l + closePathCorr);
  37179. }
  37180. // vertical distances (v)
  37181. var path1;
  37182. var path2;
  37183. var vertex1 = null;
  37184. var vertex2 = null;
  37185. for (i = 0; i < minlg + closePathCorr; i++) {
  37186. vTotalDistance[i] = 0;
  37187. vs[i] = [0];
  37188. for (p = 0; p < pathArray.length - 1; p++) {
  37189. path1 = pathArray[p];
  37190. path2 = pathArray[p + 1];
  37191. if (i === minlg) { // closePath
  37192. vertex1 = path1[0];
  37193. vertex2 = path2[0];
  37194. }
  37195. else {
  37196. vertex1 = path1[i];
  37197. vertex2 = path2[i];
  37198. }
  37199. vectlg = vertex2.subtract(vertex1).length();
  37200. dist = vectlg + vTotalDistance[i];
  37201. vs[i].push(dist);
  37202. vTotalDistance[i] = dist;
  37203. }
  37204. if (closeArray && vertex2 && vertex1) {
  37205. path1 = pathArray[p];
  37206. path2 = pathArray[0];
  37207. if (i === minlg) { // closePath
  37208. vertex2 = path2[0];
  37209. }
  37210. vectlg = vertex2.subtract(vertex1).length();
  37211. dist = vectlg + vTotalDistance[i];
  37212. vTotalDistance[i] = dist;
  37213. }
  37214. }
  37215. // uvs
  37216. var u;
  37217. var v;
  37218. if (customUV) {
  37219. for (p = 0; p < customUV.length; p++) {
  37220. uvs.push(customUV[p].x, customUV[p].y);
  37221. }
  37222. }
  37223. else {
  37224. for (p = 0; p < pathArray.length; p++) {
  37225. for (i = 0; i < minlg + closePathCorr; i++) {
  37226. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37227. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37228. if (invertUV) {
  37229. uvs.push(v, u);
  37230. }
  37231. else {
  37232. uvs.push(u, v);
  37233. }
  37234. }
  37235. }
  37236. }
  37237. // indices
  37238. p = 0; // path index
  37239. var pi = 0; // positions array index
  37240. var l1 = lg[p] - 1; // path1 length
  37241. var l2 = lg[p + 1] - 1; // path2 length
  37242. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37243. var shft = idx[1] - idx[0]; // shift
  37244. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37245. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37246. // 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
  37247. indices.push(pi, pi + shft, pi + 1);
  37248. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37249. pi += 1;
  37250. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37251. p++;
  37252. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37253. shft = idx[0] - idx[p];
  37254. l1 = lg[p] - 1;
  37255. l2 = lg[0] - 1;
  37256. }
  37257. else {
  37258. shft = idx[p + 1] - idx[p];
  37259. l1 = lg[p] - 1;
  37260. l2 = lg[p + 1] - 1;
  37261. }
  37262. pi = idx[p];
  37263. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37264. }
  37265. }
  37266. // normals
  37267. VertexData.ComputeNormals(positions, indices, normals);
  37268. if (closePath) { // update both the first and last vertex normals to their average value
  37269. var indexFirst = 0;
  37270. var indexLast = 0;
  37271. for (p = 0; p < pathArray.length; p++) {
  37272. indexFirst = idx[p] * 3;
  37273. if (p + 1 < pathArray.length) {
  37274. indexLast = (idx[p + 1] - 1) * 3;
  37275. }
  37276. else {
  37277. indexLast = normals.length - 3;
  37278. }
  37279. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37280. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37281. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37282. normals[indexLast] = normals[indexFirst];
  37283. normals[indexLast + 1] = normals[indexFirst + 1];
  37284. normals[indexLast + 2] = normals[indexFirst + 2];
  37285. }
  37286. }
  37287. // sides
  37288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37289. // Colors
  37290. var colors = null;
  37291. if (customColors) {
  37292. colors = new Float32Array(customColors.length * 4);
  37293. for (var c = 0; c < customColors.length; c++) {
  37294. colors[c * 4] = customColors[c].r;
  37295. colors[c * 4 + 1] = customColors[c].g;
  37296. colors[c * 4 + 2] = customColors[c].b;
  37297. colors[c * 4 + 3] = customColors[c].a;
  37298. }
  37299. }
  37300. // Result
  37301. var vertexData = new VertexData();
  37302. var positions32 = new Float32Array(positions);
  37303. var normals32 = new Float32Array(normals);
  37304. var uvs32 = new Float32Array(uvs);
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions32;
  37307. vertexData.normals = normals32;
  37308. vertexData.uvs = uvs32;
  37309. if (colors) {
  37310. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37311. }
  37312. if (closePath) {
  37313. vertexData._idx = idx;
  37314. }
  37315. return vertexData;
  37316. };
  37317. /**
  37318. * Creates the VertexData for a box
  37319. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37320. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37321. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37322. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37323. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37324. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37325. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37326. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37327. * * 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)
  37328. * * 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)
  37329. * @returns the VertexData of the box
  37330. */
  37331. VertexData.CreateBox = function (options) {
  37332. var normalsSource = [
  37333. new BABYLON.Vector3(0, 0, 1),
  37334. new BABYLON.Vector3(0, 0, -1),
  37335. new BABYLON.Vector3(1, 0, 0),
  37336. new BABYLON.Vector3(-1, 0, 0),
  37337. new BABYLON.Vector3(0, 1, 0),
  37338. new BABYLON.Vector3(0, -1, 0)
  37339. ];
  37340. var indices = [];
  37341. var positions = [];
  37342. var normals = [];
  37343. var uvs = [];
  37344. var width = options.width || options.size || 1;
  37345. var height = options.height || options.size || 1;
  37346. var depth = options.depth || options.size || 1;
  37347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37348. var faceUV = options.faceUV || new Array(6);
  37349. var faceColors = options.faceColors;
  37350. var colors = [];
  37351. // default face colors and UV if undefined
  37352. for (var f = 0; f < 6; f++) {
  37353. if (faceUV[f] === undefined) {
  37354. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37355. }
  37356. if (faceColors && faceColors[f] === undefined) {
  37357. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37358. }
  37359. }
  37360. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37361. // Create each face in turn.
  37362. for (var index = 0; index < normalsSource.length; index++) {
  37363. var normal = normalsSource[index];
  37364. // Get two vectors perpendicular to the face normal and to each other.
  37365. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37366. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37367. // Six indices (two triangles) per face.
  37368. var verticesLength = positions.length / 3;
  37369. indices.push(verticesLength);
  37370. indices.push(verticesLength + 1);
  37371. indices.push(verticesLength + 2);
  37372. indices.push(verticesLength);
  37373. indices.push(verticesLength + 2);
  37374. indices.push(verticesLength + 3);
  37375. // Four vertices per face.
  37376. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37377. positions.push(vertex.x, vertex.y, vertex.z);
  37378. normals.push(normal.x, normal.y, normal.z);
  37379. uvs.push(faceUV[index].z, faceUV[index].w);
  37380. if (faceColors) {
  37381. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37382. }
  37383. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37384. positions.push(vertex.x, vertex.y, vertex.z);
  37385. normals.push(normal.x, normal.y, normal.z);
  37386. uvs.push(faceUV[index].x, faceUV[index].w);
  37387. if (faceColors) {
  37388. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37389. }
  37390. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37391. positions.push(vertex.x, vertex.y, vertex.z);
  37392. normals.push(normal.x, normal.y, normal.z);
  37393. uvs.push(faceUV[index].x, faceUV[index].y);
  37394. if (faceColors) {
  37395. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37396. }
  37397. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37398. positions.push(vertex.x, vertex.y, vertex.z);
  37399. normals.push(normal.x, normal.y, normal.z);
  37400. uvs.push(faceUV[index].z, faceUV[index].y);
  37401. if (faceColors) {
  37402. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37403. }
  37404. }
  37405. // sides
  37406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37407. // Result
  37408. var vertexData = new VertexData();
  37409. vertexData.indices = indices;
  37410. vertexData.positions = positions;
  37411. vertexData.normals = normals;
  37412. vertexData.uvs = uvs;
  37413. if (faceColors) {
  37414. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37415. vertexData.colors = totalColors;
  37416. }
  37417. return vertexData;
  37418. };
  37419. /**
  37420. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37421. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37422. * * segments sets the number of horizontal strips optional, default 32
  37423. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37424. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37425. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37426. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37427. * * 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
  37428. * * 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
  37429. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37430. * * 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)
  37431. * * 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)
  37432. * @returns the VertexData of the ellipsoid
  37433. */
  37434. VertexData.CreateSphere = function (options) {
  37435. var segments = options.segments || 32;
  37436. var diameterX = options.diameterX || options.diameter || 1;
  37437. var diameterY = options.diameterY || options.diameter || 1;
  37438. var diameterZ = options.diameterZ || options.diameter || 1;
  37439. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37440. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37441. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37442. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37443. var totalZRotationSteps = 2 + segments;
  37444. var totalYRotationSteps = 2 * totalZRotationSteps;
  37445. var indices = [];
  37446. var positions = [];
  37447. var normals = [];
  37448. var uvs = [];
  37449. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37450. var normalizedZ = zRotationStep / totalZRotationSteps;
  37451. var angleZ = normalizedZ * Math.PI * slice;
  37452. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37453. var normalizedY = yRotationStep / totalYRotationSteps;
  37454. var angleY = normalizedY * Math.PI * 2 * arc;
  37455. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37456. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37457. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37458. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37459. var vertex = complete.multiply(radius);
  37460. var normal = complete.divide(radius).normalize();
  37461. positions.push(vertex.x, vertex.y, vertex.z);
  37462. normals.push(normal.x, normal.y, normal.z);
  37463. uvs.push(normalizedY, normalizedZ);
  37464. }
  37465. if (zRotationStep > 0) {
  37466. var verticesCount = positions.length / 3;
  37467. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37468. indices.push((firstIndex));
  37469. indices.push((firstIndex + 1));
  37470. indices.push(firstIndex + totalYRotationSteps + 1);
  37471. indices.push((firstIndex + totalYRotationSteps + 1));
  37472. indices.push((firstIndex + 1));
  37473. indices.push((firstIndex + totalYRotationSteps + 2));
  37474. }
  37475. }
  37476. }
  37477. // Sides
  37478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37479. // Result
  37480. var vertexData = new VertexData();
  37481. vertexData.indices = indices;
  37482. vertexData.positions = positions;
  37483. vertexData.normals = normals;
  37484. vertexData.uvs = uvs;
  37485. return vertexData;
  37486. };
  37487. /**
  37488. * Creates the VertexData for a cylinder, cone or prism
  37489. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37490. * * height sets the height (y direction) of the cylinder, optional, default 2
  37491. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37492. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37493. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37494. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37495. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37496. * * 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
  37497. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37498. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37499. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37500. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37501. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37502. * * 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)
  37503. * * 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)
  37504. * @returns the VertexData of the cylinder, cone or prism
  37505. */
  37506. VertexData.CreateCylinder = function (options) {
  37507. var height = options.height || 2;
  37508. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37509. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37510. var tessellation = options.tessellation || 24;
  37511. var subdivisions = options.subdivisions || 1;
  37512. var hasRings = options.hasRings ? true : false;
  37513. var enclose = options.enclose ? true : false;
  37514. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37516. var faceUV = options.faceUV || new Array(3);
  37517. var faceColors = options.faceColors;
  37518. // default face colors and UV if undefined
  37519. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37520. var ringNb = (hasRings) ? subdivisions : 1;
  37521. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37522. var f;
  37523. for (f = 0; f < surfaceNb; f++) {
  37524. if (faceColors && faceColors[f] === undefined) {
  37525. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37526. }
  37527. }
  37528. for (f = 0; f < surfaceNb; f++) {
  37529. if (faceUV && faceUV[f] === undefined) {
  37530. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37531. }
  37532. }
  37533. var indices = new Array();
  37534. var positions = new Array();
  37535. var normals = new Array();
  37536. var uvs = new Array();
  37537. var colors = new Array();
  37538. var angle_step = Math.PI * 2 * arc / tessellation;
  37539. var angle;
  37540. var h;
  37541. var radius;
  37542. var tan = (diameterBottom - diameterTop) / 2 / height;
  37543. var ringVertex = BABYLON.Vector3.Zero();
  37544. var ringNormal = BABYLON.Vector3.Zero();
  37545. var ringFirstVertex = BABYLON.Vector3.Zero();
  37546. var ringFirstNormal = BABYLON.Vector3.Zero();
  37547. var quadNormal = BABYLON.Vector3.Zero();
  37548. var Y = BABYLON.Axis.Y;
  37549. // positions, normals, uvs
  37550. var i;
  37551. var j;
  37552. var r;
  37553. var ringIdx = 1;
  37554. var s = 1; // surface index
  37555. var cs = 0;
  37556. var v = 0;
  37557. for (i = 0; i <= subdivisions; i++) {
  37558. h = i / subdivisions;
  37559. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37560. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37561. for (r = 0; r < ringIdx; r++) {
  37562. if (hasRings) {
  37563. s += r;
  37564. }
  37565. if (enclose) {
  37566. s += 2 * r;
  37567. }
  37568. for (j = 0; j <= tessellation; j++) {
  37569. angle = j * angle_step;
  37570. // position
  37571. ringVertex.x = Math.cos(-angle) * radius;
  37572. ringVertex.y = -height / 2 + h * height;
  37573. ringVertex.z = Math.sin(-angle) * radius;
  37574. // normal
  37575. if (diameterTop === 0 && i === subdivisions) {
  37576. // if no top cap, reuse former normals
  37577. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37578. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37579. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37580. }
  37581. else {
  37582. ringNormal.x = ringVertex.x;
  37583. ringNormal.z = ringVertex.z;
  37584. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37585. ringNormal.normalize();
  37586. }
  37587. // keep first ring vertex values for enclose
  37588. if (j === 0) {
  37589. ringFirstVertex.copyFrom(ringVertex);
  37590. ringFirstNormal.copyFrom(ringNormal);
  37591. }
  37592. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37593. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37594. if (hasRings) {
  37595. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37596. }
  37597. else {
  37598. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37599. }
  37600. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37601. if (faceColors) {
  37602. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37603. }
  37604. }
  37605. // if enclose, add four vertices and their dedicated normals
  37606. if (arc !== 1 && enclose) {
  37607. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37608. positions.push(0, ringVertex.y, 0);
  37609. positions.push(0, ringVertex.y, 0);
  37610. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37611. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37612. quadNormal.normalize();
  37613. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37614. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37615. quadNormal.normalize();
  37616. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37617. if (hasRings) {
  37618. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37619. }
  37620. else {
  37621. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37622. }
  37623. uvs.push(faceUV[s + 1].x, v);
  37624. uvs.push(faceUV[s + 1].z, v);
  37625. if (hasRings) {
  37626. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37627. }
  37628. else {
  37629. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37630. }
  37631. uvs.push(faceUV[s + 2].x, v);
  37632. uvs.push(faceUV[s + 2].z, v);
  37633. if (faceColors) {
  37634. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37635. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37636. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37637. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37638. }
  37639. }
  37640. if (cs !== s) {
  37641. cs = s;
  37642. }
  37643. }
  37644. }
  37645. // indices
  37646. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37647. var s;
  37648. i = 0;
  37649. for (s = 0; s < subdivisions; s++) {
  37650. var i0 = 0;
  37651. var i1 = 0;
  37652. var i2 = 0;
  37653. var i3 = 0;
  37654. for (j = 0; j < tessellation; j++) {
  37655. i0 = i * (e + 1) + j;
  37656. i1 = (i + 1) * (e + 1) + j;
  37657. i2 = i * (e + 1) + (j + 1);
  37658. i3 = (i + 1) * (e + 1) + (j + 1);
  37659. indices.push(i0, i1, i2);
  37660. indices.push(i3, i2, i1);
  37661. }
  37662. if (arc !== 1 && enclose) { // if enclose, add two quads
  37663. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37664. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37665. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37666. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37667. }
  37668. i = (hasRings) ? (i + 2) : (i + 1);
  37669. }
  37670. // Caps
  37671. var createCylinderCap = function (isTop) {
  37672. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37673. if (radius === 0) {
  37674. return;
  37675. }
  37676. // Cap positions, normals & uvs
  37677. var angle;
  37678. var circleVector;
  37679. var i;
  37680. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37681. var c = null;
  37682. if (faceColors) {
  37683. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37684. }
  37685. // cap center
  37686. var vbase = positions.length / 3;
  37687. var offset = isTop ? height / 2 : -height / 2;
  37688. var center = new BABYLON.Vector3(0, offset, 0);
  37689. positions.push(center.x, center.y, center.z);
  37690. normals.push(0, isTop ? 1 : -1, 0);
  37691. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37692. if (c) {
  37693. colors.push(c.r, c.g, c.b, c.a);
  37694. }
  37695. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37696. for (i = 0; i <= tessellation; i++) {
  37697. angle = Math.PI * 2 * i * arc / tessellation;
  37698. var cos = Math.cos(-angle);
  37699. var sin = Math.sin(-angle);
  37700. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37701. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37702. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37703. normals.push(0, isTop ? 1 : -1, 0);
  37704. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37705. if (c) {
  37706. colors.push(c.r, c.g, c.b, c.a);
  37707. }
  37708. }
  37709. // Cap indices
  37710. for (i = 0; i < tessellation; i++) {
  37711. if (!isTop) {
  37712. indices.push(vbase);
  37713. indices.push(vbase + (i + 1));
  37714. indices.push(vbase + (i + 2));
  37715. }
  37716. else {
  37717. indices.push(vbase);
  37718. indices.push(vbase + (i + 2));
  37719. indices.push(vbase + (i + 1));
  37720. }
  37721. }
  37722. };
  37723. // add caps to geometry
  37724. createCylinderCap(false);
  37725. createCylinderCap(true);
  37726. // Sides
  37727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37728. var vertexData = new VertexData();
  37729. vertexData.indices = indices;
  37730. vertexData.positions = positions;
  37731. vertexData.normals = normals;
  37732. vertexData.uvs = uvs;
  37733. if (faceColors) {
  37734. vertexData.colors = colors;
  37735. }
  37736. return vertexData;
  37737. };
  37738. /**
  37739. * Creates the VertexData for a torus
  37740. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37741. * * diameter the diameter of the torus, optional default 1
  37742. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37743. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37744. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37745. * * 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)
  37746. * * 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)
  37747. * @returns the VertexData of the torus
  37748. */
  37749. VertexData.CreateTorus = function (options) {
  37750. var indices = [];
  37751. var positions = [];
  37752. var normals = [];
  37753. var uvs = [];
  37754. var diameter = options.diameter || 1;
  37755. var thickness = options.thickness || 0.5;
  37756. var tessellation = options.tessellation || 16;
  37757. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37758. var stride = tessellation + 1;
  37759. for (var i = 0; i <= tessellation; i++) {
  37760. var u = i / tessellation;
  37761. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37762. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37763. for (var j = 0; j <= tessellation; j++) {
  37764. var v = 1 - j / tessellation;
  37765. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37766. var dx = Math.cos(innerAngle);
  37767. var dy = Math.sin(innerAngle);
  37768. // Create a vertex.
  37769. var normal = new BABYLON.Vector3(dx, dy, 0);
  37770. var position = normal.scale(thickness / 2);
  37771. var textureCoordinate = new BABYLON.Vector2(u, v);
  37772. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37773. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37774. positions.push(position.x, position.y, position.z);
  37775. normals.push(normal.x, normal.y, normal.z);
  37776. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37777. // And create indices for two triangles.
  37778. var nextI = (i + 1) % stride;
  37779. var nextJ = (j + 1) % stride;
  37780. indices.push(i * stride + j);
  37781. indices.push(i * stride + nextJ);
  37782. indices.push(nextI * stride + j);
  37783. indices.push(i * stride + nextJ);
  37784. indices.push(nextI * stride + nextJ);
  37785. indices.push(nextI * stride + j);
  37786. }
  37787. }
  37788. // Sides
  37789. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37790. // Result
  37791. var vertexData = new VertexData();
  37792. vertexData.indices = indices;
  37793. vertexData.positions = positions;
  37794. vertexData.normals = normals;
  37795. vertexData.uvs = uvs;
  37796. return vertexData;
  37797. };
  37798. /**
  37799. * Creates the VertexData of the LineSystem
  37800. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37801. * - lines an array of lines, each line being an array of successive Vector3
  37802. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37803. * @returns the VertexData of the LineSystem
  37804. */
  37805. VertexData.CreateLineSystem = function (options) {
  37806. var indices = [];
  37807. var positions = [];
  37808. var lines = options.lines;
  37809. var colors = options.colors;
  37810. var vertexColors = [];
  37811. var idx = 0;
  37812. for (var l = 0; l < lines.length; l++) {
  37813. var points = lines[l];
  37814. for (var index = 0; index < points.length; index++) {
  37815. positions.push(points[index].x, points[index].y, points[index].z);
  37816. if (colors) {
  37817. var color = colors[l];
  37818. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37819. }
  37820. if (index > 0) {
  37821. indices.push(idx - 1);
  37822. indices.push(idx);
  37823. }
  37824. idx++;
  37825. }
  37826. }
  37827. var vertexData = new VertexData();
  37828. vertexData.indices = indices;
  37829. vertexData.positions = positions;
  37830. if (colors) {
  37831. vertexData.colors = vertexColors;
  37832. }
  37833. return vertexData;
  37834. };
  37835. /**
  37836. * Create the VertexData for a DashedLines
  37837. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37838. * - points an array successive Vector3
  37839. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37840. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37841. * - dashNb the intended total number of dashes, optional, default 200
  37842. * @returns the VertexData for the DashedLines
  37843. */
  37844. VertexData.CreateDashedLines = function (options) {
  37845. var dashSize = options.dashSize || 3;
  37846. var gapSize = options.gapSize || 1;
  37847. var dashNb = options.dashNb || 200;
  37848. var points = options.points;
  37849. var positions = new Array();
  37850. var indices = new Array();
  37851. var curvect = BABYLON.Vector3.Zero();
  37852. var lg = 0;
  37853. var nb = 0;
  37854. var shft = 0;
  37855. var dashshft = 0;
  37856. var curshft = 0;
  37857. var idx = 0;
  37858. var i = 0;
  37859. for (i = 0; i < points.length - 1; i++) {
  37860. points[i + 1].subtractToRef(points[i], curvect);
  37861. lg += curvect.length();
  37862. }
  37863. shft = lg / dashNb;
  37864. dashshft = dashSize * shft / (dashSize + gapSize);
  37865. for (i = 0; i < points.length - 1; i++) {
  37866. points[i + 1].subtractToRef(points[i], curvect);
  37867. nb = Math.floor(curvect.length() / shft);
  37868. curvect.normalize();
  37869. for (var j = 0; j < nb; j++) {
  37870. curshft = shft * j;
  37871. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37872. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37873. indices.push(idx, idx + 1);
  37874. idx += 2;
  37875. }
  37876. }
  37877. // Result
  37878. var vertexData = new VertexData();
  37879. vertexData.positions = positions;
  37880. vertexData.indices = indices;
  37881. return vertexData;
  37882. };
  37883. /**
  37884. * Creates the VertexData for a Ground
  37885. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37886. * - width the width (x direction) of the ground, optional, default 1
  37887. * - height the height (z direction) of the ground, optional, default 1
  37888. * - subdivisions the number of subdivisions per side, optional, default 1
  37889. * @returns the VertexData of the Ground
  37890. */
  37891. VertexData.CreateGround = function (options) {
  37892. var indices = [];
  37893. var positions = [];
  37894. var normals = [];
  37895. var uvs = [];
  37896. var row, col;
  37897. var width = options.width || 1;
  37898. var height = options.height || 1;
  37899. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37900. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37901. for (row = 0; row <= subdivisionsY; row++) {
  37902. for (col = 0; col <= subdivisionsX; col++) {
  37903. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37904. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37905. positions.push(position.x, position.y, position.z);
  37906. normals.push(normal.x, normal.y, normal.z);
  37907. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37908. }
  37909. }
  37910. for (row = 0; row < subdivisionsY; row++) {
  37911. for (col = 0; col < subdivisionsX; col++) {
  37912. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37913. indices.push(col + 1 + row * (subdivisionsX + 1));
  37914. indices.push(col + row * (subdivisionsX + 1));
  37915. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37916. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37917. indices.push(col + row * (subdivisionsX + 1));
  37918. }
  37919. }
  37920. // Result
  37921. var vertexData = new VertexData();
  37922. vertexData.indices = indices;
  37923. vertexData.positions = positions;
  37924. vertexData.normals = normals;
  37925. vertexData.uvs = uvs;
  37926. return vertexData;
  37927. };
  37928. /**
  37929. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37930. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37931. * * xmin the ground minimum X coordinate, optional, default -1
  37932. * * zmin the ground minimum Z coordinate, optional, default -1
  37933. * * xmax the ground maximum X coordinate, optional, default 1
  37934. * * zmax the ground maximum Z coordinate, optional, default 1
  37935. * * 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}
  37936. * * 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}
  37937. * @returns the VertexData of the TiledGround
  37938. */
  37939. VertexData.CreateTiledGround = function (options) {
  37940. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37941. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37942. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37943. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37944. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37945. var precision = options.precision || { w: 1, h: 1 };
  37946. var indices = new Array();
  37947. var positions = new Array();
  37948. var normals = new Array();
  37949. var uvs = new Array();
  37950. var row, col, tileRow, tileCol;
  37951. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37952. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37953. precision.w = (precision.w < 1) ? 1 : precision.w;
  37954. precision.h = (precision.h < 1) ? 1 : precision.h;
  37955. var tileSize = {
  37956. 'w': (xmax - xmin) / subdivisions.w,
  37957. 'h': (zmax - zmin) / subdivisions.h
  37958. };
  37959. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37960. // Indices
  37961. var base = positions.length / 3;
  37962. var rowLength = precision.w + 1;
  37963. for (row = 0; row < precision.h; row++) {
  37964. for (col = 0; col < precision.w; col++) {
  37965. var square = [
  37966. base + col + row * rowLength,
  37967. base + (col + 1) + row * rowLength,
  37968. base + (col + 1) + (row + 1) * rowLength,
  37969. base + col + (row + 1) * rowLength
  37970. ];
  37971. indices.push(square[1]);
  37972. indices.push(square[2]);
  37973. indices.push(square[3]);
  37974. indices.push(square[0]);
  37975. indices.push(square[1]);
  37976. indices.push(square[3]);
  37977. }
  37978. }
  37979. // Position, normals and uvs
  37980. var position = BABYLON.Vector3.Zero();
  37981. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37982. for (row = 0; row <= precision.h; row++) {
  37983. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37984. for (col = 0; col <= precision.w; col++) {
  37985. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37986. position.y = 0;
  37987. positions.push(position.x, position.y, position.z);
  37988. normals.push(normal.x, normal.y, normal.z);
  37989. uvs.push(col / precision.w, row / precision.h);
  37990. }
  37991. }
  37992. }
  37993. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37994. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37995. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37996. }
  37997. }
  37998. // Result
  37999. var vertexData = new VertexData();
  38000. vertexData.indices = indices;
  38001. vertexData.positions = positions;
  38002. vertexData.normals = normals;
  38003. vertexData.uvs = uvs;
  38004. return vertexData;
  38005. };
  38006. /**
  38007. * Creates the VertexData of the Ground designed from a heightmap
  38008. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38009. * * width the width (x direction) of the ground
  38010. * * height the height (z direction) of the ground
  38011. * * subdivisions the number of subdivisions per side
  38012. * * minHeight the minimum altitude on the ground, optional, default 0
  38013. * * maxHeight the maximum altitude on the ground, optional default 1
  38014. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38015. * * buffer the array holding the image color data
  38016. * * bufferWidth the width of image
  38017. * * bufferHeight the height of image
  38018. * @returns the VertexData of the Ground designed from a heightmap
  38019. */
  38020. VertexData.CreateGroundFromHeightMap = function (options) {
  38021. var indices = [];
  38022. var positions = [];
  38023. var normals = [];
  38024. var uvs = [];
  38025. var row, col;
  38026. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38027. // Vertices
  38028. for (row = 0; row <= options.subdivisions; row++) {
  38029. for (col = 0; col <= options.subdivisions; col++) {
  38030. 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));
  38031. // Compute height
  38032. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38033. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38034. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38035. var r = options.buffer[pos] / 255.0;
  38036. var g = options.buffer[pos + 1] / 255.0;
  38037. var b = options.buffer[pos + 2] / 255.0;
  38038. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38039. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38040. // Add vertex
  38041. positions.push(position.x, position.y, position.z);
  38042. normals.push(0, 0, 0);
  38043. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38044. }
  38045. }
  38046. // Indices
  38047. for (row = 0; row < options.subdivisions; row++) {
  38048. for (col = 0; col < options.subdivisions; col++) {
  38049. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38050. indices.push(col + 1 + row * (options.subdivisions + 1));
  38051. indices.push(col + row * (options.subdivisions + 1));
  38052. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38053. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38054. indices.push(col + row * (options.subdivisions + 1));
  38055. }
  38056. }
  38057. // Normals
  38058. VertexData.ComputeNormals(positions, indices, normals);
  38059. // Result
  38060. var vertexData = new VertexData();
  38061. vertexData.indices = indices;
  38062. vertexData.positions = positions;
  38063. vertexData.normals = normals;
  38064. vertexData.uvs = uvs;
  38065. return vertexData;
  38066. };
  38067. /**
  38068. * Creates the VertexData for a Plane
  38069. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38070. * * size sets the width and height of the plane to the value of size, optional default 1
  38071. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38072. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38073. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38074. * * 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)
  38075. * * 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)
  38076. * @returns the VertexData of the box
  38077. */
  38078. VertexData.CreatePlane = function (options) {
  38079. var indices = [];
  38080. var positions = [];
  38081. var normals = [];
  38082. var uvs = [];
  38083. var width = options.width || options.size || 1;
  38084. var height = options.height || options.size || 1;
  38085. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38086. // Vertices
  38087. var halfWidth = width / 2.0;
  38088. var halfHeight = height / 2.0;
  38089. positions.push(-halfWidth, -halfHeight, 0);
  38090. normals.push(0, 0, -1.0);
  38091. uvs.push(0.0, 0.0);
  38092. positions.push(halfWidth, -halfHeight, 0);
  38093. normals.push(0, 0, -1.0);
  38094. uvs.push(1.0, 0.0);
  38095. positions.push(halfWidth, halfHeight, 0);
  38096. normals.push(0, 0, -1.0);
  38097. uvs.push(1.0, 1.0);
  38098. positions.push(-halfWidth, halfHeight, 0);
  38099. normals.push(0, 0, -1.0);
  38100. uvs.push(0.0, 1.0);
  38101. // Indices
  38102. indices.push(0);
  38103. indices.push(1);
  38104. indices.push(2);
  38105. indices.push(0);
  38106. indices.push(2);
  38107. indices.push(3);
  38108. // Sides
  38109. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38110. // Result
  38111. var vertexData = new VertexData();
  38112. vertexData.indices = indices;
  38113. vertexData.positions = positions;
  38114. vertexData.normals = normals;
  38115. vertexData.uvs = uvs;
  38116. return vertexData;
  38117. };
  38118. /**
  38119. * Creates the VertexData of the Disc or regular Polygon
  38120. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38121. * * radius the radius of the disc, optional default 0.5
  38122. * * tessellation the number of polygon sides, optional, default 64
  38123. * * 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
  38124. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38125. * * 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)
  38126. * * 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)
  38127. * @returns the VertexData of the box
  38128. */
  38129. VertexData.CreateDisc = function (options) {
  38130. var positions = new Array();
  38131. var indices = new Array();
  38132. var normals = new Array();
  38133. var uvs = new Array();
  38134. var radius = options.radius || 0.5;
  38135. var tessellation = options.tessellation || 64;
  38136. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38138. // positions and uvs
  38139. positions.push(0, 0, 0); // disc center first
  38140. uvs.push(0.5, 0.5);
  38141. var theta = Math.PI * 2 * arc;
  38142. var step = theta / tessellation;
  38143. for (var a = 0; a < theta; a += step) {
  38144. var x = Math.cos(a);
  38145. var y = Math.sin(a);
  38146. var u = (x + 1) / 2;
  38147. var v = (1 - y) / 2;
  38148. positions.push(radius * x, radius * y, 0);
  38149. uvs.push(u, v);
  38150. }
  38151. if (arc === 1) {
  38152. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38153. uvs.push(uvs[2], uvs[3]);
  38154. }
  38155. //indices
  38156. var vertexNb = positions.length / 3;
  38157. for (var i = 1; i < vertexNb - 1; i++) {
  38158. indices.push(i + 1, 0, i);
  38159. }
  38160. // result
  38161. VertexData.ComputeNormals(positions, indices, normals);
  38162. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38163. var vertexData = new VertexData();
  38164. vertexData.indices = indices;
  38165. vertexData.positions = positions;
  38166. vertexData.normals = normals;
  38167. vertexData.uvs = uvs;
  38168. return vertexData;
  38169. };
  38170. /**
  38171. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38172. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38173. * @param polygon a mesh built from polygonTriangulation.build()
  38174. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38175. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38176. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38177. * @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)
  38178. * @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)
  38179. * @returns the VertexData of the Polygon
  38180. */
  38181. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38182. var faceUV = fUV || new Array(3);
  38183. var faceColors = fColors;
  38184. var colors = [];
  38185. // default face colors and UV if undefined
  38186. for (var f = 0; f < 3; f++) {
  38187. if (faceUV[f] === undefined) {
  38188. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38189. }
  38190. if (faceColors && faceColors[f] === undefined) {
  38191. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38192. }
  38193. }
  38194. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38195. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38196. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38197. var indices = polygon.getIndices();
  38198. // set face colours and textures
  38199. var idx = 0;
  38200. var face = 0;
  38201. for (var index = 0; index < normals.length; index += 3) {
  38202. //Edge Face no. 1
  38203. if (Math.abs(normals[index + 1]) < 0.001) {
  38204. face = 1;
  38205. }
  38206. //Top Face no. 0
  38207. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38208. face = 0;
  38209. }
  38210. //Bottom Face no. 2
  38211. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38212. face = 2;
  38213. }
  38214. idx = index / 3;
  38215. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38216. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38217. if (faceColors) {
  38218. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38219. }
  38220. }
  38221. // sides
  38222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38223. // Result
  38224. var vertexData = new VertexData();
  38225. vertexData.indices = indices;
  38226. vertexData.positions = positions;
  38227. vertexData.normals = normals;
  38228. vertexData.uvs = uvs;
  38229. if (faceColors) {
  38230. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38231. vertexData.colors = totalColors;
  38232. }
  38233. return vertexData;
  38234. };
  38235. /**
  38236. * Creates the VertexData of the IcoSphere
  38237. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38238. * * radius the radius of the IcoSphere, optional default 1
  38239. * * radiusX allows stretching in the x direction, optional, default radius
  38240. * * radiusY allows stretching in the y direction, optional, default radius
  38241. * * radiusZ allows stretching in the z direction, optional, default radius
  38242. * * flat when true creates a flat shaded mesh, optional, default true
  38243. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38244. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38245. * * 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)
  38246. * * 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)
  38247. * @returns the VertexData of the IcoSphere
  38248. */
  38249. VertexData.CreateIcoSphere = function (options) {
  38250. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38251. var radius = options.radius || 1;
  38252. var flat = (options.flat === undefined) ? true : options.flat;
  38253. var subdivisions = options.subdivisions || 4;
  38254. var radiusX = options.radiusX || radius;
  38255. var radiusY = options.radiusY || radius;
  38256. var radiusZ = options.radiusZ || radius;
  38257. var t = (1 + Math.sqrt(5)) / 2;
  38258. // 12 vertex x,y,z
  38259. var ico_vertices = [
  38260. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38261. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38262. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38263. ];
  38264. // index of 3 vertex makes a face of icopshere
  38265. var ico_indices = [
  38266. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38267. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38268. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38269. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38270. ];
  38271. // vertex for uv have aliased position, not for UV
  38272. var vertices_unalias_id = [
  38273. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38274. // vertex alias
  38275. 0,
  38276. 2,
  38277. 3,
  38278. 3,
  38279. 3,
  38280. 4,
  38281. 7,
  38282. 8,
  38283. 9,
  38284. 9,
  38285. 10,
  38286. 11 // 23: B + 12
  38287. ];
  38288. // uv as integer step (not pixels !)
  38289. var ico_vertexuv = [
  38290. 5, 1, 3, 1, 6, 4, 0, 0,
  38291. 5, 3, 4, 2, 2, 2, 4, 0,
  38292. 2, 0, 1, 1, 6, 0, 6, 2,
  38293. // vertex alias (for same vertex on different faces)
  38294. 0, 4,
  38295. 3, 3,
  38296. 4, 4,
  38297. 3, 1,
  38298. 4, 2,
  38299. 4, 4,
  38300. 0, 2,
  38301. 1, 1,
  38302. 2, 2,
  38303. 3, 3,
  38304. 1, 3,
  38305. 2, 4 // 23: B + 12
  38306. ];
  38307. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38308. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38309. // First island of uv mapping
  38310. // v = 4h 3+ 2
  38311. // v = 3h 9+ 4
  38312. // v = 2h 9+ 5 B
  38313. // v = 1h 9 1 0
  38314. // v = 0h 3 8 7 A
  38315. // u = 0 1 2 3 4 5 6 *a
  38316. // Second island of uv mapping
  38317. // v = 4h 0+ B+ 4+
  38318. // v = 3h A+ 2+
  38319. // v = 2h 7+ 6 3+
  38320. // v = 1h 8+ 3+
  38321. // v = 0h
  38322. // u = 0 1 2 3 4 5 6 *a
  38323. // Face layout on texture UV mapping
  38324. // ============
  38325. // \ 4 /\ 16 / ======
  38326. // \ / \ / /\ 11 /
  38327. // \/ 7 \/ / \ /
  38328. // ======= / 10 \/
  38329. // /\ 17 /\ =======
  38330. // / \ / \ \ 15 /\
  38331. // / 8 \/ 12 \ \ / \
  38332. // ============ \/ 6 \
  38333. // \ 18 /\ ============
  38334. // \ / \ \ 5 /\ 0 /
  38335. // \/ 13 \ \ / \ /
  38336. // ======= \/ 1 \/
  38337. // =============
  38338. // /\ 19 /\ 2 /\
  38339. // / \ / \ / \
  38340. // / 14 \/ 9 \/ 3 \
  38341. // ===================
  38342. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38343. var ustep = 138 / 1024;
  38344. var vstep = 239 / 1024;
  38345. var uoffset = 60 / 1024;
  38346. var voffset = 26 / 1024;
  38347. // Second island should have margin, not to touch the first island
  38348. // avoid any borderline artefact in pixel rounding
  38349. var island_u_offset = -40 / 1024;
  38350. var island_v_offset = +20 / 1024;
  38351. // face is either island 0 or 1 :
  38352. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38353. var island = [
  38354. 0, 0, 0, 0, 1,
  38355. 0, 0, 1, 1, 0,
  38356. 0, 0, 1, 1, 0,
  38357. 0, 1, 1, 1, 0 // 15 - 19
  38358. ];
  38359. var indices = new Array();
  38360. var positions = new Array();
  38361. var normals = new Array();
  38362. var uvs = new Array();
  38363. var current_indice = 0;
  38364. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38365. var face_vertex_pos = new Array(3);
  38366. var face_vertex_uv = new Array(3);
  38367. var v012;
  38368. for (v012 = 0; v012 < 3; v012++) {
  38369. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38370. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38371. }
  38372. // create all with normals
  38373. for (var face = 0; face < 20; face++) {
  38374. // 3 vertex per face
  38375. for (v012 = 0; v012 < 3; v012++) {
  38376. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38377. var v_id = ico_indices[3 * face + v012];
  38378. // vertex have 3D position (x,y,z)
  38379. 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]);
  38380. // Normalize to get normal, then scale to radius
  38381. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38382. // uv Coordinates from vertex ID
  38383. 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);
  38384. }
  38385. // Subdivide the face (interpolate pos, norm, uv)
  38386. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38387. // - norm is linear interpolation of vertex corner normal
  38388. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38389. // - uv is linear interpolation
  38390. //
  38391. // Topology is as below for sub-divide by 2
  38392. // vertex shown as v0,v1,v2
  38393. // interp index is i1 to progress in range [v0,v1[
  38394. // interp index is i2 to progress in range [v0,v2[
  38395. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38396. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38397. //
  38398. //
  38399. // i2 v2
  38400. // ^ ^
  38401. // / / \
  38402. // / / \
  38403. // / / \
  38404. // / / (0,1) \
  38405. // / #---------\
  38406. // / / \ (0,0)'/ \
  38407. // / / \ / \
  38408. // / / \ / \
  38409. // / / (0,0) \ / (1,0) \
  38410. // / #---------#---------\
  38411. // v0 v1
  38412. //
  38413. // --------------------> i1
  38414. //
  38415. // interp of (i1,i2):
  38416. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38417. // along i1 : lerp(x0,x1, i1/(S-i2))
  38418. //
  38419. // centroid of triangle is needed to get help normal computation
  38420. // (c1,c2) are used for centroid location
  38421. var interp_vertex = function (i1, i2, c1, c2) {
  38422. // vertex is interpolated from
  38423. // - face_vertex_pos[0..2]
  38424. // - face_vertex_uv[0..2]
  38425. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38426. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38427. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38428. pos_interp.normalize();
  38429. var vertex_normal;
  38430. if (flat) {
  38431. // in flat mode, recalculate normal as face centroid normal
  38432. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38433. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38434. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38435. }
  38436. else {
  38437. // in smooth mode, recalculate normal from each single vertex position
  38438. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38439. }
  38440. // Vertex normal need correction due to X,Y,Z radius scaling
  38441. vertex_normal.x /= radiusX;
  38442. vertex_normal.y /= radiusY;
  38443. vertex_normal.z /= radiusZ;
  38444. vertex_normal.normalize();
  38445. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38446. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38447. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38448. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38449. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38450. uvs.push(uv_interp.x, uv_interp.y);
  38451. // push each vertex has member of a face
  38452. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38453. indices.push(current_indice);
  38454. current_indice++;
  38455. };
  38456. for (var i2 = 0; i2 < subdivisions; i2++) {
  38457. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38458. // face : (i1,i2) for /\ :
  38459. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38460. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38461. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38462. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38463. if (i1 + i2 + 1 < subdivisions) {
  38464. // face : (i1,i2)' for \/ :
  38465. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38466. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38467. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38468. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38469. }
  38470. }
  38471. }
  38472. }
  38473. // Sides
  38474. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38475. // Result
  38476. var vertexData = new VertexData();
  38477. vertexData.indices = indices;
  38478. vertexData.positions = positions;
  38479. vertexData.normals = normals;
  38480. vertexData.uvs = uvs;
  38481. return vertexData;
  38482. };
  38483. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38484. /**
  38485. * Creates the VertexData for a Polyhedron
  38486. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38487. * * type provided types are:
  38488. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38489. * * 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)
  38490. * * size the size of the IcoSphere, optional default 1
  38491. * * sizeX allows stretching in the x direction, optional, default size
  38492. * * sizeY allows stretching in the y direction, optional, default size
  38493. * * sizeZ allows stretching in the z direction, optional, default size
  38494. * * 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
  38495. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38496. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38497. * * flat when true creates a flat shaded mesh, optional, default true
  38498. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38499. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38500. * * 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)
  38501. * * 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)
  38502. * @returns the VertexData of the Polyhedron
  38503. */
  38504. VertexData.CreatePolyhedron = function (options) {
  38505. // provided polyhedron types :
  38506. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38507. // 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)
  38508. var polyhedra = [];
  38509. 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]] };
  38510. 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]] };
  38511. polyhedra[2] = {
  38512. 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]],
  38513. 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]]
  38514. };
  38515. polyhedra[3] = {
  38516. 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]],
  38517. 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]]
  38518. };
  38519. polyhedra[4] = {
  38520. 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]],
  38521. 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]]
  38522. };
  38523. 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]] };
  38524. 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]] };
  38525. 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]] };
  38526. 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]] };
  38527. 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]] };
  38528. 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]] };
  38529. 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]] };
  38530. 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]] };
  38531. 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]] };
  38532. polyhedra[14] = {
  38533. 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]],
  38534. 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]]
  38535. };
  38536. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38537. var size = options.size;
  38538. var sizeX = options.sizeX || size || 1;
  38539. var sizeY = options.sizeY || size || 1;
  38540. var sizeZ = options.sizeZ || size || 1;
  38541. var data = options.custom || polyhedra[type];
  38542. var nbfaces = data.face.length;
  38543. var faceUV = options.faceUV || new Array(nbfaces);
  38544. var faceColors = options.faceColors;
  38545. var flat = (options.flat === undefined) ? true : options.flat;
  38546. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38547. var positions = new Array();
  38548. var indices = new Array();
  38549. var normals = new Array();
  38550. var uvs = new Array();
  38551. var colors = new Array();
  38552. var index = 0;
  38553. var faceIdx = 0; // face cursor in the array "indexes"
  38554. var indexes = new Array();
  38555. var i = 0;
  38556. var f = 0;
  38557. var u, v, ang, x, y, tmp;
  38558. // default face colors and UV if undefined
  38559. if (flat) {
  38560. for (f = 0; f < nbfaces; f++) {
  38561. if (faceColors && faceColors[f] === undefined) {
  38562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38563. }
  38564. if (faceUV && faceUV[f] === undefined) {
  38565. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38566. }
  38567. }
  38568. }
  38569. if (!flat) {
  38570. for (i = 0; i < data.vertex.length; i++) {
  38571. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38572. uvs.push(0, 0);
  38573. }
  38574. for (f = 0; f < nbfaces; f++) {
  38575. for (i = 0; i < data.face[f].length - 2; i++) {
  38576. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38577. }
  38578. }
  38579. }
  38580. else {
  38581. for (f = 0; f < nbfaces; f++) {
  38582. var fl = data.face[f].length; // number of vertices of the current face
  38583. ang = 2 * Math.PI / fl;
  38584. x = 0.5 * Math.tan(ang / 2);
  38585. y = 0.5;
  38586. // positions, uvs, colors
  38587. for (i = 0; i < fl; i++) {
  38588. // positions
  38589. 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);
  38590. indexes.push(index);
  38591. index++;
  38592. // uvs
  38593. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38594. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38595. uvs.push(u, v);
  38596. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38597. y = x * Math.sin(ang) + y * Math.cos(ang);
  38598. x = tmp;
  38599. // colors
  38600. if (faceColors) {
  38601. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38602. }
  38603. }
  38604. // indices from indexes
  38605. for (i = 0; i < fl - 2; i++) {
  38606. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38607. }
  38608. faceIdx += fl;
  38609. }
  38610. }
  38611. VertexData.ComputeNormals(positions, indices, normals);
  38612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38613. var vertexData = new VertexData();
  38614. vertexData.positions = positions;
  38615. vertexData.indices = indices;
  38616. vertexData.normals = normals;
  38617. vertexData.uvs = uvs;
  38618. if (faceColors && flat) {
  38619. vertexData.colors = colors;
  38620. }
  38621. return vertexData;
  38622. };
  38623. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38624. /**
  38625. * Creates the VertexData for a TorusKnot
  38626. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38627. * * radius the radius of the torus knot, optional, default 2
  38628. * * tube the thickness of the tube, optional, default 0.5
  38629. * * radialSegments the number of sides on each tube segments, optional, default 32
  38630. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38631. * * p the number of windings around the z axis, optional, default 2
  38632. * * q the number of windings around the x axis, optional, default 3
  38633. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38634. * * 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)
  38635. * * 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)
  38636. * @returns the VertexData of the Torus Knot
  38637. */
  38638. VertexData.CreateTorusKnot = function (options) {
  38639. var indices = new Array();
  38640. var positions = new Array();
  38641. var normals = new Array();
  38642. var uvs = new Array();
  38643. var radius = options.radius || 2;
  38644. var tube = options.tube || 0.5;
  38645. var radialSegments = options.radialSegments || 32;
  38646. var tubularSegments = options.tubularSegments || 32;
  38647. var p = options.p || 2;
  38648. var q = options.q || 3;
  38649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38650. // Helper
  38651. var getPos = function (angle) {
  38652. var cu = Math.cos(angle);
  38653. var su = Math.sin(angle);
  38654. var quOverP = q / p * angle;
  38655. var cs = Math.cos(quOverP);
  38656. var tx = radius * (2 + cs) * 0.5 * cu;
  38657. var ty = radius * (2 + cs) * su * 0.5;
  38658. var tz = radius * Math.sin(quOverP) * 0.5;
  38659. return new BABYLON.Vector3(tx, ty, tz);
  38660. };
  38661. // Vertices
  38662. var i;
  38663. var j;
  38664. for (i = 0; i <= radialSegments; i++) {
  38665. var modI = i % radialSegments;
  38666. var u = modI / radialSegments * 2 * p * Math.PI;
  38667. var p1 = getPos(u);
  38668. var p2 = getPos(u + 0.01);
  38669. var tang = p2.subtract(p1);
  38670. var n = p2.add(p1);
  38671. var bitan = BABYLON.Vector3.Cross(tang, n);
  38672. n = BABYLON.Vector3.Cross(bitan, tang);
  38673. bitan.normalize();
  38674. n.normalize();
  38675. for (j = 0; j < tubularSegments; j++) {
  38676. var modJ = j % tubularSegments;
  38677. var v = modJ / tubularSegments * 2 * Math.PI;
  38678. var cx = -tube * Math.cos(v);
  38679. var cy = tube * Math.sin(v);
  38680. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38681. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38682. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38683. uvs.push(i / radialSegments);
  38684. uvs.push(j / tubularSegments);
  38685. }
  38686. }
  38687. for (i = 0; i < radialSegments; i++) {
  38688. for (j = 0; j < tubularSegments; j++) {
  38689. var jNext = (j + 1) % tubularSegments;
  38690. var a = i * tubularSegments + j;
  38691. var b = (i + 1) * tubularSegments + j;
  38692. var c = (i + 1) * tubularSegments + jNext;
  38693. var d = i * tubularSegments + jNext;
  38694. indices.push(d);
  38695. indices.push(b);
  38696. indices.push(a);
  38697. indices.push(d);
  38698. indices.push(c);
  38699. indices.push(b);
  38700. }
  38701. }
  38702. // Normals
  38703. VertexData.ComputeNormals(positions, indices, normals);
  38704. // Sides
  38705. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38706. // Result
  38707. var vertexData = new VertexData();
  38708. vertexData.indices = indices;
  38709. vertexData.positions = positions;
  38710. vertexData.normals = normals;
  38711. vertexData.uvs = uvs;
  38712. return vertexData;
  38713. };
  38714. // Tools
  38715. /**
  38716. * Compute normals for given positions and indices
  38717. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38718. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38719. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38720. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38721. * * facetNormals : optional array of facet normals (vector3)
  38722. * * facetPositions : optional array of facet positions (vector3)
  38723. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38724. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38725. * * bInfo : optional bounding info, required for facetPartitioning computation
  38726. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38727. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38728. * * useRightHandedSystem: optional boolean to for right handed system computation
  38729. * * depthSort : optional boolean to enable the facet depth sort computation
  38730. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38731. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38732. */
  38733. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38734. // temporary scalar variables
  38735. var index = 0; // facet index
  38736. var p1p2x = 0.0; // p1p2 vector x coordinate
  38737. var p1p2y = 0.0; // p1p2 vector y coordinate
  38738. var p1p2z = 0.0; // p1p2 vector z coordinate
  38739. var p3p2x = 0.0; // p3p2 vector x coordinate
  38740. var p3p2y = 0.0; // p3p2 vector y coordinate
  38741. var p3p2z = 0.0; // p3p2 vector z coordinate
  38742. var faceNormalx = 0.0; // facet normal x coordinate
  38743. var faceNormaly = 0.0; // facet normal y coordinate
  38744. var faceNormalz = 0.0; // facet normal z coordinate
  38745. var length = 0.0; // facet normal length before normalization
  38746. var v1x = 0; // vector1 x index in the positions array
  38747. var v1y = 0; // vector1 y index in the positions array
  38748. var v1z = 0; // vector1 z index in the positions array
  38749. var v2x = 0; // vector2 x index in the positions array
  38750. var v2y = 0; // vector2 y index in the positions array
  38751. var v2z = 0; // vector2 z index in the positions array
  38752. var v3x = 0; // vector3 x index in the positions array
  38753. var v3y = 0; // vector3 y index in the positions array
  38754. var v3z = 0; // vector3 z index in the positions array
  38755. var computeFacetNormals = false;
  38756. var computeFacetPositions = false;
  38757. var computeFacetPartitioning = false;
  38758. var computeDepthSort = false;
  38759. var faceNormalSign = 1;
  38760. var ratio = 0;
  38761. var distanceTo = null;
  38762. if (options) {
  38763. computeFacetNormals = (options.facetNormals) ? true : false;
  38764. computeFacetPositions = (options.facetPositions) ? true : false;
  38765. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38766. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38767. ratio = options.ratio || 0;
  38768. computeDepthSort = (options.depthSort) ? true : false;
  38769. distanceTo = (options.distanceTo);
  38770. if (computeDepthSort) {
  38771. if (distanceTo === undefined) {
  38772. distanceTo = BABYLON.Vector3.Zero();
  38773. }
  38774. var depthSortedFacets = options.depthSortedFacets;
  38775. }
  38776. }
  38777. // facetPartitioning reinit if needed
  38778. var xSubRatio = 0;
  38779. var ySubRatio = 0;
  38780. var zSubRatio = 0;
  38781. var subSq = 0;
  38782. if (computeFacetPartitioning && options && options.bbSize) {
  38783. var ox = 0; // X partitioning index for facet position
  38784. var oy = 0; // Y partinioning index for facet position
  38785. var oz = 0; // Z partinioning index for facet position
  38786. var b1x = 0; // X partitioning index for facet v1 vertex
  38787. var b1y = 0; // Y partitioning index for facet v1 vertex
  38788. var b1z = 0; // z partitioning index for facet v1 vertex
  38789. var b2x = 0; // X partitioning index for facet v2 vertex
  38790. var b2y = 0; // Y partitioning index for facet v2 vertex
  38791. var b2z = 0; // Z partitioning index for facet v2 vertex
  38792. var b3x = 0; // X partitioning index for facet v3 vertex
  38793. var b3y = 0; // Y partitioning index for facet v3 vertex
  38794. var b3z = 0; // Z partitioning index for facet v3 vertex
  38795. var block_idx_o = 0; // facet barycenter block index
  38796. var block_idx_v1 = 0; // v1 vertex block index
  38797. var block_idx_v2 = 0; // v2 vertex block index
  38798. var block_idx_v3 = 0; // v3 vertex block index
  38799. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38800. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38801. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38802. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38803. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38804. subSq = options.subDiv.max * options.subDiv.max;
  38805. options.facetPartitioning.length = 0;
  38806. }
  38807. // reset the normals
  38808. for (index = 0; index < positions.length; index++) {
  38809. normals[index] = 0.0;
  38810. }
  38811. // Loop : 1 indice triplet = 1 facet
  38812. var nbFaces = (indices.length / 3) | 0;
  38813. for (index = 0; index < nbFaces; index++) {
  38814. // get the indexes of the coordinates of each vertex of the facet
  38815. v1x = indices[index * 3] * 3;
  38816. v1y = v1x + 1;
  38817. v1z = v1x + 2;
  38818. v2x = indices[index * 3 + 1] * 3;
  38819. v2y = v2x + 1;
  38820. v2z = v2x + 2;
  38821. v3x = indices[index * 3 + 2] * 3;
  38822. v3y = v3x + 1;
  38823. v3z = v3x + 2;
  38824. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38825. p1p2y = positions[v1y] - positions[v2y];
  38826. p1p2z = positions[v1z] - positions[v2z];
  38827. p3p2x = positions[v3x] - positions[v2x];
  38828. p3p2y = positions[v3y] - positions[v2y];
  38829. p3p2z = positions[v3z] - positions[v2z];
  38830. // compute the face normal with the cross product
  38831. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38832. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38833. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38834. // normalize this normal and store it in the array facetData
  38835. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38836. length = (length === 0) ? 1.0 : length;
  38837. faceNormalx /= length;
  38838. faceNormaly /= length;
  38839. faceNormalz /= length;
  38840. if (computeFacetNormals && options) {
  38841. options.facetNormals[index].x = faceNormalx;
  38842. options.facetNormals[index].y = faceNormaly;
  38843. options.facetNormals[index].z = faceNormalz;
  38844. }
  38845. if (computeFacetPositions && options) {
  38846. // compute and the facet barycenter coordinates in the array facetPositions
  38847. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38848. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38849. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38850. }
  38851. if (computeFacetPartitioning && options) {
  38852. // store the facet indexes in arrays in the main facetPartitioning array :
  38853. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38854. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38855. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38856. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38857. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38858. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38859. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38860. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38861. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38862. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38863. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38864. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38865. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38866. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38867. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38868. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38869. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38870. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38871. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38872. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38873. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38874. // push each facet index in each block containing the vertex
  38875. options.facetPartitioning[block_idx_v1].push(index);
  38876. if (block_idx_v2 != block_idx_v1) {
  38877. options.facetPartitioning[block_idx_v2].push(index);
  38878. }
  38879. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38880. options.facetPartitioning[block_idx_v3].push(index);
  38881. }
  38882. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38883. options.facetPartitioning[block_idx_o].push(index);
  38884. }
  38885. }
  38886. if (computeDepthSort && options && options.facetPositions) {
  38887. var dsf = depthSortedFacets[index];
  38888. dsf.ind = index * 3;
  38889. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38890. }
  38891. // compute the normals anyway
  38892. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38893. normals[v1y] += faceNormaly;
  38894. normals[v1z] += faceNormalz;
  38895. normals[v2x] += faceNormalx;
  38896. normals[v2y] += faceNormaly;
  38897. normals[v2z] += faceNormalz;
  38898. normals[v3x] += faceNormalx;
  38899. normals[v3y] += faceNormaly;
  38900. normals[v3z] += faceNormalz;
  38901. }
  38902. // last normalization of each normal
  38903. for (index = 0; index < normals.length / 3; index++) {
  38904. faceNormalx = normals[index * 3];
  38905. faceNormaly = normals[index * 3 + 1];
  38906. faceNormalz = normals[index * 3 + 2];
  38907. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38908. length = (length === 0) ? 1.0 : length;
  38909. faceNormalx /= length;
  38910. faceNormaly /= length;
  38911. faceNormalz /= length;
  38912. normals[index * 3] = faceNormalx;
  38913. normals[index * 3 + 1] = faceNormaly;
  38914. normals[index * 3 + 2] = faceNormalz;
  38915. }
  38916. };
  38917. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38918. var li = indices.length;
  38919. var ln = normals.length;
  38920. var i;
  38921. var n;
  38922. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38923. switch (sideOrientation) {
  38924. case BABYLON.Mesh.FRONTSIDE:
  38925. // nothing changed
  38926. break;
  38927. case BABYLON.Mesh.BACKSIDE:
  38928. var tmp;
  38929. // indices
  38930. for (i = 0; i < li; i += 3) {
  38931. tmp = indices[i];
  38932. indices[i] = indices[i + 2];
  38933. indices[i + 2] = tmp;
  38934. }
  38935. // normals
  38936. for (n = 0; n < ln; n++) {
  38937. normals[n] = -normals[n];
  38938. }
  38939. break;
  38940. case BABYLON.Mesh.DOUBLESIDE:
  38941. // positions
  38942. var lp = positions.length;
  38943. var l = lp / 3;
  38944. for (var p = 0; p < lp; p++) {
  38945. positions[lp + p] = positions[p];
  38946. }
  38947. // indices
  38948. for (i = 0; i < li; i += 3) {
  38949. indices[i + li] = indices[i + 2] + l;
  38950. indices[i + 1 + li] = indices[i + 1] + l;
  38951. indices[i + 2 + li] = indices[i] + l;
  38952. }
  38953. // normals
  38954. for (n = 0; n < ln; n++) {
  38955. normals[ln + n] = -normals[n];
  38956. }
  38957. // uvs
  38958. var lu = uvs.length;
  38959. var u = 0;
  38960. for (u = 0; u < lu; u++) {
  38961. uvs[u + lu] = uvs[u];
  38962. }
  38963. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38964. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38965. u = 0;
  38966. for (i = 0; i < lu / 2; i++) {
  38967. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38968. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38969. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38970. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38971. u += 2;
  38972. }
  38973. break;
  38974. }
  38975. };
  38976. /**
  38977. * Applies VertexData created from the imported parameters to the geometry
  38978. * @param parsedVertexData the parsed data from an imported file
  38979. * @param geometry the geometry to apply the VertexData to
  38980. */
  38981. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38982. var vertexData = new VertexData();
  38983. // positions
  38984. var positions = parsedVertexData.positions;
  38985. if (positions) {
  38986. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38987. }
  38988. // normals
  38989. var normals = parsedVertexData.normals;
  38990. if (normals) {
  38991. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38992. }
  38993. // tangents
  38994. var tangents = parsedVertexData.tangents;
  38995. if (tangents) {
  38996. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38997. }
  38998. // uvs
  38999. var uvs = parsedVertexData.uvs;
  39000. if (uvs) {
  39001. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39002. }
  39003. // uv2s
  39004. var uv2s = parsedVertexData.uv2s;
  39005. if (uv2s) {
  39006. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39007. }
  39008. // uv3s
  39009. var uv3s = parsedVertexData.uv3s;
  39010. if (uv3s) {
  39011. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39012. }
  39013. // uv4s
  39014. var uv4s = parsedVertexData.uv4s;
  39015. if (uv4s) {
  39016. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39017. }
  39018. // uv5s
  39019. var uv5s = parsedVertexData.uv5s;
  39020. if (uv5s) {
  39021. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39022. }
  39023. // uv6s
  39024. var uv6s = parsedVertexData.uv6s;
  39025. if (uv6s) {
  39026. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39027. }
  39028. // colors
  39029. var colors = parsedVertexData.colors;
  39030. if (colors) {
  39031. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39032. }
  39033. // matricesIndices
  39034. var matricesIndices = parsedVertexData.matricesIndices;
  39035. if (matricesIndices) {
  39036. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39037. }
  39038. // matricesWeights
  39039. var matricesWeights = parsedVertexData.matricesWeights;
  39040. if (matricesWeights) {
  39041. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39042. }
  39043. // indices
  39044. var indices = parsedVertexData.indices;
  39045. if (indices) {
  39046. vertexData.indices = indices;
  39047. }
  39048. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39049. };
  39050. return VertexData;
  39051. }());
  39052. BABYLON.VertexData = VertexData;
  39053. })(BABYLON || (BABYLON = {}));
  39054. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39055. var BABYLON;
  39056. (function (BABYLON) {
  39057. /**
  39058. * Class used to store geometry data (vertex buffers + index buffer)
  39059. */
  39060. var Geometry = /** @class */ (function () {
  39061. /**
  39062. * Creates a new geometry
  39063. * @param id defines the unique ID
  39064. * @param scene defines the hosting scene
  39065. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39066. * @param updatable defines if geometry must be updatable (false by default)
  39067. * @param mesh defines the mesh that will be associated with the geometry
  39068. */
  39069. function Geometry(id, scene, vertexData, updatable, mesh) {
  39070. if (updatable === void 0) { updatable = false; }
  39071. if (mesh === void 0) { mesh = null; }
  39072. /**
  39073. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39074. */
  39075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39076. this._totalVertices = 0;
  39077. this._isDisposed = false;
  39078. this._indexBufferIsUpdatable = false;
  39079. this.id = id;
  39080. this._engine = scene.getEngine();
  39081. this._meshes = [];
  39082. this._scene = scene;
  39083. //Init vertex buffer cache
  39084. this._vertexBuffers = {};
  39085. this._indices = [];
  39086. this._updatable = updatable;
  39087. // vertexData
  39088. if (vertexData) {
  39089. this.setAllVerticesData(vertexData, updatable);
  39090. }
  39091. else {
  39092. this._totalVertices = 0;
  39093. this._indices = [];
  39094. }
  39095. if (this._engine.getCaps().vertexArrayObject) {
  39096. this._vertexArrayObjects = {};
  39097. }
  39098. // applyToMesh
  39099. if (mesh) {
  39100. if (mesh.getClassName() === "LinesMesh") {
  39101. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39102. this._updateExtend();
  39103. }
  39104. this.applyToMesh(mesh);
  39105. mesh.computeWorldMatrix(true);
  39106. }
  39107. }
  39108. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39109. /**
  39110. * 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
  39111. */
  39112. get: function () {
  39113. return this._boundingBias;
  39114. },
  39115. /**
  39116. * 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
  39117. */
  39118. set: function (value) {
  39119. if (this._boundingBias && this._boundingBias.equals(value)) {
  39120. return;
  39121. }
  39122. this._boundingBias = value.clone();
  39123. this._updateBoundingInfo(true, null);
  39124. },
  39125. enumerable: true,
  39126. configurable: true
  39127. });
  39128. /**
  39129. * Static function used to attach a new empty geometry to a mesh
  39130. * @param mesh defines the mesh to attach the geometry to
  39131. * @returns the new {BABYLON.Geometry}
  39132. */
  39133. Geometry.CreateGeometryForMesh = function (mesh) {
  39134. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39135. geometry.applyToMesh(mesh);
  39136. return geometry;
  39137. };
  39138. Object.defineProperty(Geometry.prototype, "extend", {
  39139. /**
  39140. * Gets the current extend of the geometry
  39141. */
  39142. get: function () {
  39143. return this._extend;
  39144. },
  39145. enumerable: true,
  39146. configurable: true
  39147. });
  39148. /**
  39149. * Gets the hosting scene
  39150. * @returns the hosting {BABYLON.Scene}
  39151. */
  39152. Geometry.prototype.getScene = function () {
  39153. return this._scene;
  39154. };
  39155. /**
  39156. * Gets the hosting engine
  39157. * @returns the hosting {BABYLON.Engine}
  39158. */
  39159. Geometry.prototype.getEngine = function () {
  39160. return this._engine;
  39161. };
  39162. /**
  39163. * Defines if the geometry is ready to use
  39164. * @returns true if the geometry is ready to be used
  39165. */
  39166. Geometry.prototype.isReady = function () {
  39167. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39168. };
  39169. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39170. /**
  39171. * Gets a value indicating that the geometry should not be serialized
  39172. */
  39173. get: function () {
  39174. for (var index = 0; index < this._meshes.length; index++) {
  39175. if (!this._meshes[index].doNotSerialize) {
  39176. return false;
  39177. }
  39178. }
  39179. return true;
  39180. },
  39181. enumerable: true,
  39182. configurable: true
  39183. });
  39184. /** @hidden */
  39185. Geometry.prototype._rebuild = function () {
  39186. if (this._vertexArrayObjects) {
  39187. this._vertexArrayObjects = {};
  39188. }
  39189. // Index buffer
  39190. if (this._meshes.length !== 0 && this._indices) {
  39191. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39192. }
  39193. // Vertex buffers
  39194. for (var key in this._vertexBuffers) {
  39195. var vertexBuffer = this._vertexBuffers[key];
  39196. vertexBuffer._rebuild();
  39197. }
  39198. };
  39199. /**
  39200. * Affects all geometry data in one call
  39201. * @param vertexData defines the geometry data
  39202. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39203. */
  39204. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39205. vertexData.applyToGeometry(this, updatable);
  39206. this.notifyUpdate();
  39207. };
  39208. /**
  39209. * Set specific vertex data
  39210. * @param kind defines the data kind (Position, normal, etc...)
  39211. * @param data defines the vertex data to use
  39212. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39213. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39214. */
  39215. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39216. if (updatable === void 0) { updatable = false; }
  39217. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39218. this.setVerticesBuffer(buffer);
  39219. };
  39220. /**
  39221. * Removes a specific vertex data
  39222. * @param kind defines the data kind (Position, normal, etc...)
  39223. */
  39224. Geometry.prototype.removeVerticesData = function (kind) {
  39225. if (this._vertexBuffers[kind]) {
  39226. this._vertexBuffers[kind].dispose();
  39227. delete this._vertexBuffers[kind];
  39228. }
  39229. };
  39230. /**
  39231. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39232. * @param buffer defines the vertex buffer to use
  39233. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39234. */
  39235. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39236. if (totalVertices === void 0) { totalVertices = null; }
  39237. var kind = buffer.getKind();
  39238. if (this._vertexBuffers[kind]) {
  39239. this._vertexBuffers[kind].dispose();
  39240. }
  39241. this._vertexBuffers[kind] = buffer;
  39242. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39243. var data = buffer.getData();
  39244. if (totalVertices != null) {
  39245. this._totalVertices = totalVertices;
  39246. }
  39247. else {
  39248. if (data != null) {
  39249. this._totalVertices = data.length / (buffer.byteStride / 4);
  39250. }
  39251. }
  39252. this._updateExtend(data);
  39253. this._resetPointsArrayCache();
  39254. var meshes = this._meshes;
  39255. var numOfMeshes = meshes.length;
  39256. for (var index = 0; index < numOfMeshes; index++) {
  39257. var mesh = meshes[index];
  39258. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39259. mesh._createGlobalSubMesh(false);
  39260. mesh.computeWorldMatrix(true);
  39261. }
  39262. }
  39263. this.notifyUpdate(kind);
  39264. if (this._vertexArrayObjects) {
  39265. this._disposeVertexArrayObjects();
  39266. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39267. }
  39268. };
  39269. /**
  39270. * Update a specific vertex buffer
  39271. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39272. * It will do nothing if the buffer is not updatable
  39273. * @param kind defines the data kind (Position, normal, etc...)
  39274. * @param data defines the data to use
  39275. * @param offset defines the offset in the target buffer where to store the data
  39276. * @param useBytes set to true if the offset is in bytes
  39277. */
  39278. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39279. if (useBytes === void 0) { useBytes = false; }
  39280. var vertexBuffer = this.getVertexBuffer(kind);
  39281. if (!vertexBuffer) {
  39282. return;
  39283. }
  39284. vertexBuffer.updateDirectly(data, offset, useBytes);
  39285. this.notifyUpdate(kind);
  39286. };
  39287. /**
  39288. * Update a specific vertex buffer
  39289. * This function will create a new buffer if the current one is not updatable
  39290. * @param kind defines the data kind (Position, normal, etc...)
  39291. * @param data defines the data to use
  39292. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39293. */
  39294. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39295. if (updateExtends === void 0) { updateExtends = false; }
  39296. var vertexBuffer = this.getVertexBuffer(kind);
  39297. if (!vertexBuffer) {
  39298. return;
  39299. }
  39300. vertexBuffer.update(data);
  39301. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39302. this._updateBoundingInfo(updateExtends, data);
  39303. }
  39304. this.notifyUpdate(kind);
  39305. };
  39306. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39307. if (updateExtends) {
  39308. this._updateExtend(data);
  39309. }
  39310. var meshes = this._meshes;
  39311. var numOfMeshes = meshes.length;
  39312. this._resetPointsArrayCache();
  39313. for (var index = 0; index < numOfMeshes; index++) {
  39314. var mesh = meshes[index];
  39315. if (updateExtends) {
  39316. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39317. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39318. var subMesh = mesh.subMeshes[subIndex];
  39319. subMesh.refreshBoundingInfo();
  39320. }
  39321. }
  39322. }
  39323. };
  39324. /** @hidden */
  39325. Geometry.prototype._bind = function (effect, indexToBind) {
  39326. if (!effect) {
  39327. return;
  39328. }
  39329. if (indexToBind === undefined) {
  39330. indexToBind = this._indexBuffer;
  39331. }
  39332. var vbs = this.getVertexBuffers();
  39333. if (!vbs) {
  39334. return;
  39335. }
  39336. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39337. this._engine.bindBuffers(vbs, indexToBind, effect);
  39338. return;
  39339. }
  39340. // Using VAO
  39341. if (!this._vertexArrayObjects[effect.key]) {
  39342. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39343. }
  39344. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39345. };
  39346. /**
  39347. * Gets total number of vertices
  39348. * @returns the total number of vertices
  39349. */
  39350. Geometry.prototype.getTotalVertices = function () {
  39351. if (!this.isReady()) {
  39352. return 0;
  39353. }
  39354. return this._totalVertices;
  39355. };
  39356. /**
  39357. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39358. * @param kind defines the data kind (Position, normal, etc...)
  39359. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39360. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39361. * @returns a float array containing vertex data
  39362. */
  39363. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39364. var vertexBuffer = this.getVertexBuffer(kind);
  39365. if (!vertexBuffer) {
  39366. return null;
  39367. }
  39368. var data = vertexBuffer.getData();
  39369. if (!data) {
  39370. return null;
  39371. }
  39372. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39373. var count = this._totalVertices * vertexBuffer.getSize();
  39374. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39375. var copy_1 = new Array(count);
  39376. vertexBuffer.forEach(count, function (value, index) {
  39377. copy_1[index] = value;
  39378. });
  39379. return copy_1;
  39380. }
  39381. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39382. if (data instanceof Array) {
  39383. var offset = vertexBuffer.byteOffset / 4;
  39384. return BABYLON.Tools.Slice(data, offset, offset + count);
  39385. }
  39386. else if (data instanceof ArrayBuffer) {
  39387. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39388. }
  39389. else {
  39390. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39391. }
  39392. }
  39393. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39394. return BABYLON.Tools.Slice(data);
  39395. }
  39396. return data;
  39397. };
  39398. /**
  39399. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39400. * @param kind defines the data kind (Position, normal, etc...)
  39401. * @returns true if the vertex buffer with the specified kind is updatable
  39402. */
  39403. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39404. var vb = this._vertexBuffers[kind];
  39405. if (!vb) {
  39406. return false;
  39407. }
  39408. return vb.isUpdatable();
  39409. };
  39410. /**
  39411. * Gets a specific vertex buffer
  39412. * @param kind defines the data kind (Position, normal, etc...)
  39413. * @returns a {BABYLON.VertexBuffer}
  39414. */
  39415. Geometry.prototype.getVertexBuffer = function (kind) {
  39416. if (!this.isReady()) {
  39417. return null;
  39418. }
  39419. return this._vertexBuffers[kind];
  39420. };
  39421. /**
  39422. * Returns all vertex buffers
  39423. * @return an object holding all vertex buffers indexed by kind
  39424. */
  39425. Geometry.prototype.getVertexBuffers = function () {
  39426. if (!this.isReady()) {
  39427. return null;
  39428. }
  39429. return this._vertexBuffers;
  39430. };
  39431. /**
  39432. * Gets a boolean indicating if specific vertex buffer is present
  39433. * @param kind defines the data kind (Position, normal, etc...)
  39434. * @returns true if data is present
  39435. */
  39436. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39437. if (!this._vertexBuffers) {
  39438. if (this._delayInfo) {
  39439. return this._delayInfo.indexOf(kind) !== -1;
  39440. }
  39441. return false;
  39442. }
  39443. return this._vertexBuffers[kind] !== undefined;
  39444. };
  39445. /**
  39446. * Gets a list of all attached data kinds (Position, normal, etc...)
  39447. * @returns a list of string containing all kinds
  39448. */
  39449. Geometry.prototype.getVerticesDataKinds = function () {
  39450. var result = [];
  39451. var kind;
  39452. if (!this._vertexBuffers && this._delayInfo) {
  39453. for (kind in this._delayInfo) {
  39454. result.push(kind);
  39455. }
  39456. }
  39457. else {
  39458. for (kind in this._vertexBuffers) {
  39459. result.push(kind);
  39460. }
  39461. }
  39462. return result;
  39463. };
  39464. /**
  39465. * Update index buffer
  39466. * @param indices defines the indices to store in the index buffer
  39467. * @param offset defines the offset in the target buffer where to store the data
  39468. */
  39469. Geometry.prototype.updateIndices = function (indices, offset) {
  39470. if (!this._indexBuffer) {
  39471. return;
  39472. }
  39473. if (!this._indexBufferIsUpdatable) {
  39474. this.setIndices(indices, null, true);
  39475. }
  39476. else {
  39477. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39478. }
  39479. };
  39480. /**
  39481. * Creates a new index buffer
  39482. * @param indices defines the indices to store in the index buffer
  39483. * @param totalVertices defines the total number of vertices (could be null)
  39484. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39485. */
  39486. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39487. if (totalVertices === void 0) { totalVertices = null; }
  39488. if (updatable === void 0) { updatable = false; }
  39489. if (this._indexBuffer) {
  39490. this._engine._releaseBuffer(this._indexBuffer);
  39491. }
  39492. this._disposeVertexArrayObjects();
  39493. this._indices = indices;
  39494. this._indexBufferIsUpdatable = updatable;
  39495. if (this._meshes.length !== 0 && this._indices) {
  39496. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39497. }
  39498. if (totalVertices != undefined) { // including null and undefined
  39499. this._totalVertices = totalVertices;
  39500. }
  39501. var meshes = this._meshes;
  39502. var numOfMeshes = meshes.length;
  39503. for (var index = 0; index < numOfMeshes; index++) {
  39504. meshes[index]._createGlobalSubMesh(true);
  39505. }
  39506. this.notifyUpdate();
  39507. };
  39508. /**
  39509. * Return the total number of indices
  39510. * @returns the total number of indices
  39511. */
  39512. Geometry.prototype.getTotalIndices = function () {
  39513. if (!this.isReady()) {
  39514. return 0;
  39515. }
  39516. return this._indices.length;
  39517. };
  39518. /**
  39519. * Gets the index buffer array
  39520. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39521. * @returns the index buffer array
  39522. */
  39523. Geometry.prototype.getIndices = function (copyWhenShared) {
  39524. if (!this.isReady()) {
  39525. return null;
  39526. }
  39527. var orig = this._indices;
  39528. if (!copyWhenShared || this._meshes.length === 1) {
  39529. return orig;
  39530. }
  39531. else {
  39532. var len = orig.length;
  39533. var copy = [];
  39534. for (var i = 0; i < len; i++) {
  39535. copy.push(orig[i]);
  39536. }
  39537. return copy;
  39538. }
  39539. };
  39540. /**
  39541. * Gets the index buffer
  39542. * @return the index buffer
  39543. */
  39544. Geometry.prototype.getIndexBuffer = function () {
  39545. if (!this.isReady()) {
  39546. return null;
  39547. }
  39548. return this._indexBuffer;
  39549. };
  39550. /** @hidden */
  39551. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39552. if (effect === void 0) { effect = null; }
  39553. if (!effect || !this._vertexArrayObjects) {
  39554. return;
  39555. }
  39556. if (this._vertexArrayObjects[effect.key]) {
  39557. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39558. delete this._vertexArrayObjects[effect.key];
  39559. }
  39560. };
  39561. /**
  39562. * Release the associated resources for a specific mesh
  39563. * @param mesh defines the source mesh
  39564. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39565. */
  39566. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39567. var meshes = this._meshes;
  39568. var index = meshes.indexOf(mesh);
  39569. if (index === -1) {
  39570. return;
  39571. }
  39572. meshes.splice(index, 1);
  39573. mesh._geometry = null;
  39574. if (meshes.length === 0 && shouldDispose) {
  39575. this.dispose();
  39576. }
  39577. };
  39578. /**
  39579. * Apply current geometry to a given mesh
  39580. * @param mesh defines the mesh to apply geometry to
  39581. */
  39582. Geometry.prototype.applyToMesh = function (mesh) {
  39583. if (mesh._geometry === this) {
  39584. return;
  39585. }
  39586. var previousGeometry = mesh._geometry;
  39587. if (previousGeometry) {
  39588. previousGeometry.releaseForMesh(mesh);
  39589. }
  39590. var meshes = this._meshes;
  39591. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39592. mesh._geometry = this;
  39593. this._scene.pushGeometry(this);
  39594. meshes.push(mesh);
  39595. if (this.isReady()) {
  39596. this._applyToMesh(mesh);
  39597. }
  39598. else {
  39599. mesh._boundingInfo = this._boundingInfo;
  39600. }
  39601. };
  39602. Geometry.prototype._updateExtend = function (data) {
  39603. if (data === void 0) { data = null; }
  39604. if (!data) {
  39605. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39606. }
  39607. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39608. };
  39609. Geometry.prototype._applyToMesh = function (mesh) {
  39610. var numOfMeshes = this._meshes.length;
  39611. // vertexBuffers
  39612. for (var kind in this._vertexBuffers) {
  39613. if (numOfMeshes === 1) {
  39614. this._vertexBuffers[kind].create();
  39615. }
  39616. var buffer = this._vertexBuffers[kind].getBuffer();
  39617. if (buffer)
  39618. buffer.references = numOfMeshes;
  39619. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39620. if (!this._extend) {
  39621. this._updateExtend();
  39622. }
  39623. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39624. mesh._createGlobalSubMesh(false);
  39625. //bounding info was just created again, world matrix should be applied again.
  39626. mesh._updateBoundingInfo();
  39627. }
  39628. }
  39629. // indexBuffer
  39630. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39631. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39632. }
  39633. if (this._indexBuffer) {
  39634. this._indexBuffer.references = numOfMeshes;
  39635. }
  39636. };
  39637. Geometry.prototype.notifyUpdate = function (kind) {
  39638. if (this.onGeometryUpdated) {
  39639. this.onGeometryUpdated(this, kind);
  39640. }
  39641. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39642. var mesh = _a[_i];
  39643. mesh._markSubMeshesAsAttributesDirty();
  39644. }
  39645. };
  39646. /**
  39647. * Load the geometry if it was flagged as delay loaded
  39648. * @param scene defines the hosting scene
  39649. * @param onLoaded defines a callback called when the geometry is loaded
  39650. */
  39651. Geometry.prototype.load = function (scene, onLoaded) {
  39652. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39653. return;
  39654. }
  39655. if (this.isReady()) {
  39656. if (onLoaded) {
  39657. onLoaded();
  39658. }
  39659. return;
  39660. }
  39661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39662. this._queueLoad(scene, onLoaded);
  39663. };
  39664. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39665. var _this = this;
  39666. if (!this.delayLoadingFile) {
  39667. return;
  39668. }
  39669. scene._addPendingData(this);
  39670. scene._loadFile(this.delayLoadingFile, function (data) {
  39671. if (!_this._delayLoadingFunction) {
  39672. return;
  39673. }
  39674. _this._delayLoadingFunction(JSON.parse(data), _this);
  39675. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39676. _this._delayInfo = [];
  39677. scene._removePendingData(_this);
  39678. var meshes = _this._meshes;
  39679. var numOfMeshes = meshes.length;
  39680. for (var index = 0; index < numOfMeshes; index++) {
  39681. _this._applyToMesh(meshes[index]);
  39682. }
  39683. if (onLoaded) {
  39684. onLoaded();
  39685. }
  39686. }, undefined, true);
  39687. };
  39688. /**
  39689. * Invert the geometry to move from a right handed system to a left handed one.
  39690. */
  39691. Geometry.prototype.toLeftHanded = function () {
  39692. // Flip faces
  39693. var tIndices = this.getIndices(false);
  39694. if (tIndices != null && tIndices.length > 0) {
  39695. for (var i = 0; i < tIndices.length; i += 3) {
  39696. var tTemp = tIndices[i + 0];
  39697. tIndices[i + 0] = tIndices[i + 2];
  39698. tIndices[i + 2] = tTemp;
  39699. }
  39700. this.setIndices(tIndices);
  39701. }
  39702. // Negate position.z
  39703. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39704. if (tPositions != null && tPositions.length > 0) {
  39705. for (var i = 0; i < tPositions.length; i += 3) {
  39706. tPositions[i + 2] = -tPositions[i + 2];
  39707. }
  39708. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39709. }
  39710. // Negate normal.z
  39711. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39712. if (tNormals != null && tNormals.length > 0) {
  39713. for (var i = 0; i < tNormals.length; i += 3) {
  39714. tNormals[i + 2] = -tNormals[i + 2];
  39715. }
  39716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39717. }
  39718. };
  39719. // Cache
  39720. /** @hidden */
  39721. Geometry.prototype._resetPointsArrayCache = function () {
  39722. this._positions = null;
  39723. };
  39724. /** @hidden */
  39725. Geometry.prototype._generatePointsArray = function () {
  39726. if (this._positions)
  39727. return true;
  39728. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39729. if (!data || data.length === 0) {
  39730. return false;
  39731. }
  39732. this._positions = [];
  39733. for (var index = 0; index < data.length; index += 3) {
  39734. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39735. }
  39736. return true;
  39737. };
  39738. /**
  39739. * Gets a value indicating if the geometry is disposed
  39740. * @returns true if the geometry was disposed
  39741. */
  39742. Geometry.prototype.isDisposed = function () {
  39743. return this._isDisposed;
  39744. };
  39745. Geometry.prototype._disposeVertexArrayObjects = function () {
  39746. if (this._vertexArrayObjects) {
  39747. for (var kind in this._vertexArrayObjects) {
  39748. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39749. }
  39750. this._vertexArrayObjects = {};
  39751. }
  39752. };
  39753. /**
  39754. * Free all associated resources
  39755. */
  39756. Geometry.prototype.dispose = function () {
  39757. var meshes = this._meshes;
  39758. var numOfMeshes = meshes.length;
  39759. var index;
  39760. for (index = 0; index < numOfMeshes; index++) {
  39761. this.releaseForMesh(meshes[index]);
  39762. }
  39763. this._meshes = [];
  39764. this._disposeVertexArrayObjects();
  39765. for (var kind in this._vertexBuffers) {
  39766. this._vertexBuffers[kind].dispose();
  39767. }
  39768. this._vertexBuffers = {};
  39769. this._totalVertices = 0;
  39770. if (this._indexBuffer) {
  39771. this._engine._releaseBuffer(this._indexBuffer);
  39772. }
  39773. this._indexBuffer = null;
  39774. this._indices = [];
  39775. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39776. this.delayLoadingFile = null;
  39777. this._delayLoadingFunction = null;
  39778. this._delayInfo = [];
  39779. this._boundingInfo = null;
  39780. this._scene.removeGeometry(this);
  39781. this._isDisposed = true;
  39782. };
  39783. /**
  39784. * Clone the current geometry into a new geometry
  39785. * @param id defines the unique ID of the new geometry
  39786. * @returns a new geometry object
  39787. */
  39788. Geometry.prototype.copy = function (id) {
  39789. var vertexData = new BABYLON.VertexData();
  39790. vertexData.indices = [];
  39791. var indices = this.getIndices();
  39792. if (indices) {
  39793. for (var index = 0; index < indices.length; index++) {
  39794. vertexData.indices.push(indices[index]);
  39795. }
  39796. }
  39797. var updatable = false;
  39798. var stopChecking = false;
  39799. var kind;
  39800. for (kind in this._vertexBuffers) {
  39801. // using slice() to make a copy of the array and not just reference it
  39802. var data = this.getVerticesData(kind);
  39803. if (data instanceof Float32Array) {
  39804. vertexData.set(new Float32Array(data), kind);
  39805. }
  39806. else {
  39807. vertexData.set(data.slice(0), kind);
  39808. }
  39809. if (!stopChecking) {
  39810. var vb = this.getVertexBuffer(kind);
  39811. if (vb) {
  39812. updatable = vb.isUpdatable();
  39813. stopChecking = !updatable;
  39814. }
  39815. }
  39816. }
  39817. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39818. geometry.delayLoadState = this.delayLoadState;
  39819. geometry.delayLoadingFile = this.delayLoadingFile;
  39820. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39821. for (kind in this._delayInfo) {
  39822. geometry._delayInfo = geometry._delayInfo || [];
  39823. geometry._delayInfo.push(kind);
  39824. }
  39825. // Bounding info
  39826. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39827. return geometry;
  39828. };
  39829. /**
  39830. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39831. * @return a JSON representation of the current geometry data (without the vertices data)
  39832. */
  39833. Geometry.prototype.serialize = function () {
  39834. var serializationObject = {};
  39835. serializationObject.id = this.id;
  39836. serializationObject.updatable = this._updatable;
  39837. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39838. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39839. }
  39840. return serializationObject;
  39841. };
  39842. Geometry.prototype.toNumberArray = function (origin) {
  39843. if (Array.isArray(origin)) {
  39844. return origin;
  39845. }
  39846. else {
  39847. return Array.prototype.slice.call(origin);
  39848. }
  39849. };
  39850. /**
  39851. * Serialize all vertices data into a JSON oject
  39852. * @returns a JSON representation of the current geometry data
  39853. */
  39854. Geometry.prototype.serializeVerticeData = function () {
  39855. var serializationObject = this.serialize();
  39856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39857. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39858. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39859. serializationObject.positions._updatable = true;
  39860. }
  39861. }
  39862. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39863. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39864. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39865. serializationObject.normals._updatable = true;
  39866. }
  39867. }
  39868. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39869. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39870. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39871. serializationObject.tangets._updatable = true;
  39872. }
  39873. }
  39874. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39875. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39876. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39877. serializationObject.uvs._updatable = true;
  39878. }
  39879. }
  39880. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39881. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39882. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39883. serializationObject.uv2s._updatable = true;
  39884. }
  39885. }
  39886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39887. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39889. serializationObject.uv3s._updatable = true;
  39890. }
  39891. }
  39892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39893. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39895. serializationObject.uv4s._updatable = true;
  39896. }
  39897. }
  39898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39899. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39900. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39901. serializationObject.uv5s._updatable = true;
  39902. }
  39903. }
  39904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39905. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39907. serializationObject.uv6s._updatable = true;
  39908. }
  39909. }
  39910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39911. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39913. serializationObject.colors._updatable = true;
  39914. }
  39915. }
  39916. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39917. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39918. serializationObject.matricesIndices._isExpanded = true;
  39919. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39920. serializationObject.matricesIndices._updatable = true;
  39921. }
  39922. }
  39923. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39924. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39925. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39926. serializationObject.matricesWeights._updatable = true;
  39927. }
  39928. }
  39929. serializationObject.indices = this.toNumberArray(this.getIndices());
  39930. return serializationObject;
  39931. };
  39932. // Statics
  39933. /**
  39934. * Extracts a clone of a mesh geometry
  39935. * @param mesh defines the source mesh
  39936. * @param id defines the unique ID of the new geometry object
  39937. * @returns the new geometry object
  39938. */
  39939. Geometry.ExtractFromMesh = function (mesh, id) {
  39940. var geometry = mesh._geometry;
  39941. if (!geometry) {
  39942. return null;
  39943. }
  39944. return geometry.copy(id);
  39945. };
  39946. /**
  39947. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39948. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39949. * Be aware Math.random() could cause collisions, but:
  39950. * "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"
  39951. * @returns a string containing a new GUID
  39952. */
  39953. Geometry.RandomId = function () {
  39954. return BABYLON.Tools.RandomId();
  39955. };
  39956. /** @hidden */
  39957. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39958. var scene = mesh.getScene();
  39959. // Geometry
  39960. var geometryId = parsedGeometry.geometryId;
  39961. if (geometryId) {
  39962. var geometry = scene.getGeometryByID(geometryId);
  39963. if (geometry) {
  39964. geometry.applyToMesh(mesh);
  39965. }
  39966. }
  39967. else if (parsedGeometry instanceof ArrayBuffer) {
  39968. var binaryInfo = mesh._binaryInfo;
  39969. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39970. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39971. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39972. }
  39973. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39974. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39976. }
  39977. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39978. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39980. }
  39981. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39982. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39983. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39984. }
  39985. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39986. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39988. }
  39989. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39990. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39991. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39992. }
  39993. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39994. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39995. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39996. }
  39997. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39998. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39999. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40000. }
  40001. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40002. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40004. }
  40005. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40006. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40007. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40008. }
  40009. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40010. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40012. }
  40013. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40014. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40016. }
  40017. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40018. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40019. mesh.setIndices(indicesData, null);
  40020. }
  40021. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40022. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40023. mesh.subMeshes = [];
  40024. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40025. var materialIndex = subMeshesData[(i * 5) + 0];
  40026. var verticesStart = subMeshesData[(i * 5) + 1];
  40027. var verticesCount = subMeshesData[(i * 5) + 2];
  40028. var indexStart = subMeshesData[(i * 5) + 3];
  40029. var indexCount = subMeshesData[(i * 5) + 4];
  40030. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40031. }
  40032. }
  40033. }
  40034. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40035. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40036. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40037. if (parsedGeometry.tangents) {
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40039. }
  40040. if (parsedGeometry.uvs) {
  40041. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40042. }
  40043. if (parsedGeometry.uvs2) {
  40044. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40045. }
  40046. if (parsedGeometry.uvs3) {
  40047. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40048. }
  40049. if (parsedGeometry.uvs4) {
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40051. }
  40052. if (parsedGeometry.uvs5) {
  40053. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40054. }
  40055. if (parsedGeometry.uvs6) {
  40056. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40057. }
  40058. if (parsedGeometry.colors) {
  40059. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40060. }
  40061. if (parsedGeometry.matricesIndices) {
  40062. if (!parsedGeometry.matricesIndices._isExpanded) {
  40063. var floatIndices = [];
  40064. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40065. var matricesIndex = parsedGeometry.matricesIndices[i];
  40066. floatIndices.push(matricesIndex & 0x000000FF);
  40067. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40068. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40069. floatIndices.push(matricesIndex >> 24);
  40070. }
  40071. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40072. }
  40073. else {
  40074. delete parsedGeometry.matricesIndices._isExpanded;
  40075. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40076. }
  40077. }
  40078. if (parsedGeometry.matricesIndicesExtra) {
  40079. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40080. var floatIndices = [];
  40081. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40082. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40083. floatIndices.push(matricesIndex & 0x000000FF);
  40084. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40085. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40086. floatIndices.push(matricesIndex >> 24);
  40087. }
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40089. }
  40090. else {
  40091. delete parsedGeometry.matricesIndices._isExpanded;
  40092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40093. }
  40094. }
  40095. if (parsedGeometry.matricesWeights) {
  40096. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40097. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40098. }
  40099. if (parsedGeometry.matricesWeightsExtra) {
  40100. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40101. }
  40102. mesh.setIndices(parsedGeometry.indices, null);
  40103. }
  40104. // SubMeshes
  40105. if (parsedGeometry.subMeshes) {
  40106. mesh.subMeshes = [];
  40107. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40108. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40109. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40110. }
  40111. }
  40112. // Flat shading
  40113. if (mesh._shouldGenerateFlatShading) {
  40114. mesh.convertToFlatShadedMesh();
  40115. delete mesh._shouldGenerateFlatShading;
  40116. }
  40117. // Update
  40118. mesh.computeWorldMatrix(true);
  40119. // Octree
  40120. var sceneOctree = scene.selectionOctree;
  40121. if (sceneOctree !== undefined && sceneOctree !== null) {
  40122. sceneOctree.addMesh(mesh);
  40123. }
  40124. };
  40125. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40126. var epsilon = 1e-3;
  40127. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40128. return;
  40129. }
  40130. var noInfluenceBoneIndex = 0.0;
  40131. if (parsedGeometry.skeletonId > -1) {
  40132. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40133. if (!skeleton) {
  40134. return;
  40135. }
  40136. noInfluenceBoneIndex = skeleton.bones.length;
  40137. }
  40138. else {
  40139. return;
  40140. }
  40141. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40142. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40143. var matricesWeights = parsedGeometry.matricesWeights;
  40144. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40145. var influencers = parsedGeometry.numBoneInfluencer;
  40146. var size = matricesWeights.length;
  40147. for (var i = 0; i < size; i += 4) {
  40148. var weight = 0.0;
  40149. var firstZeroWeight = -1;
  40150. for (var j = 0; j < 4; j++) {
  40151. var w = matricesWeights[i + j];
  40152. weight += w;
  40153. if (w < epsilon && firstZeroWeight < 0) {
  40154. firstZeroWeight = j;
  40155. }
  40156. }
  40157. if (matricesWeightsExtra) {
  40158. for (var j = 0; j < 4; j++) {
  40159. var w = matricesWeightsExtra[i + j];
  40160. weight += w;
  40161. if (w < epsilon && firstZeroWeight < 0) {
  40162. firstZeroWeight = j + 4;
  40163. }
  40164. }
  40165. }
  40166. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40167. firstZeroWeight = influencers - 1;
  40168. }
  40169. if (weight > epsilon) {
  40170. var mweight = 1.0 / weight;
  40171. for (var j = 0; j < 4; j++) {
  40172. matricesWeights[i + j] *= mweight;
  40173. }
  40174. if (matricesWeightsExtra) {
  40175. for (var j = 0; j < 4; j++) {
  40176. matricesWeightsExtra[i + j] *= mweight;
  40177. }
  40178. }
  40179. }
  40180. else {
  40181. if (firstZeroWeight >= 4) {
  40182. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40183. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40184. }
  40185. else {
  40186. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40187. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40188. }
  40189. }
  40190. }
  40191. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40192. if (parsedGeometry.matricesWeightsExtra) {
  40193. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40194. }
  40195. };
  40196. /**
  40197. * Create a new geometry from persisted data (Using .babylon file format)
  40198. * @param parsedVertexData defines the persisted data
  40199. * @param scene defines the hosting scene
  40200. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40201. * @returns the new geometry object
  40202. */
  40203. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40204. if (scene.getGeometryByID(parsedVertexData.id)) {
  40205. return null; // null since geometry could be something else than a box...
  40206. }
  40207. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40208. if (BABYLON.Tags) {
  40209. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40210. }
  40211. if (parsedVertexData.delayLoadingFile) {
  40212. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40213. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40214. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40215. geometry._delayInfo = [];
  40216. if (parsedVertexData.hasUVs) {
  40217. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40218. }
  40219. if (parsedVertexData.hasUVs2) {
  40220. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40221. }
  40222. if (parsedVertexData.hasUVs3) {
  40223. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40224. }
  40225. if (parsedVertexData.hasUVs4) {
  40226. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40227. }
  40228. if (parsedVertexData.hasUVs5) {
  40229. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40230. }
  40231. if (parsedVertexData.hasUVs6) {
  40232. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40233. }
  40234. if (parsedVertexData.hasColors) {
  40235. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40236. }
  40237. if (parsedVertexData.hasMatricesIndices) {
  40238. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40239. }
  40240. if (parsedVertexData.hasMatricesWeights) {
  40241. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40242. }
  40243. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40244. }
  40245. else {
  40246. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40247. }
  40248. scene.pushGeometry(geometry, true);
  40249. return geometry;
  40250. };
  40251. return Geometry;
  40252. }());
  40253. BABYLON.Geometry = Geometry;
  40254. // Primitives
  40255. /// Abstract class
  40256. /**
  40257. * Abstract class used to provide common services for all typed geometries
  40258. * @hidden
  40259. */
  40260. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40261. __extends(_PrimitiveGeometry, _super);
  40262. /**
  40263. * Creates a new typed geometry
  40264. * @param id defines the unique ID of the geometry
  40265. * @param scene defines the hosting scene
  40266. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40267. * @param mesh defines the hosting mesh (can be null)
  40268. */
  40269. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40270. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40271. if (mesh === void 0) { mesh = null; }
  40272. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40273. _this._canBeRegenerated = _canBeRegenerated;
  40274. _this._beingRegenerated = true;
  40275. _this.regenerate();
  40276. _this._beingRegenerated = false;
  40277. return _this;
  40278. }
  40279. /**
  40280. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40281. * @returns true if the geometry can be regenerated
  40282. */
  40283. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40284. return this._canBeRegenerated;
  40285. };
  40286. /**
  40287. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40288. */
  40289. _PrimitiveGeometry.prototype.regenerate = function () {
  40290. if (!this._canBeRegenerated) {
  40291. return;
  40292. }
  40293. this._beingRegenerated = true;
  40294. this.setAllVerticesData(this._regenerateVertexData(), false);
  40295. this._beingRegenerated = false;
  40296. };
  40297. /**
  40298. * Clone the geometry
  40299. * @param id defines the unique ID of the new geometry
  40300. * @returns the new geometry
  40301. */
  40302. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40303. return _super.prototype.copy.call(this, id);
  40304. };
  40305. // overrides
  40306. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40307. if (!this._beingRegenerated) {
  40308. return;
  40309. }
  40310. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40311. };
  40312. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40313. if (!this._beingRegenerated) {
  40314. return;
  40315. }
  40316. _super.prototype.setVerticesData.call(this, kind, data, false);
  40317. };
  40318. // to override
  40319. /** @hidden */
  40320. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40321. throw new Error("Abstract method");
  40322. };
  40323. _PrimitiveGeometry.prototype.copy = function (id) {
  40324. throw new Error("Must be overriden in sub-classes.");
  40325. };
  40326. _PrimitiveGeometry.prototype.serialize = function () {
  40327. var serializationObject = _super.prototype.serialize.call(this);
  40328. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40329. return serializationObject;
  40330. };
  40331. return _PrimitiveGeometry;
  40332. }(Geometry));
  40333. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40334. /**
  40335. * Creates a ribbon geometry
  40336. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40337. */
  40338. var RibbonGeometry = /** @class */ (function (_super) {
  40339. __extends(RibbonGeometry, _super);
  40340. /**
  40341. * Creates a ribbon geometry
  40342. * @param id defines the unique ID of the geometry
  40343. * @param scene defines the hosting scene
  40344. * @param pathArray defines the array of paths to use
  40345. * @param closeArray defines if the last path and the first path must be joined
  40346. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40347. * @param offset defines the offset between points
  40348. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40349. * @param mesh defines the hosting mesh (can be null)
  40350. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40351. */
  40352. function RibbonGeometry(id, scene,
  40353. /**
  40354. * Defines the array of paths to use
  40355. */
  40356. pathArray,
  40357. /**
  40358. * Defines if the last and first points of each path in your pathArray must be joined
  40359. */
  40360. closeArray,
  40361. /**
  40362. * Defines if the last and first points of each path in your pathArray must be joined
  40363. */
  40364. closePath,
  40365. /**
  40366. * Defines the offset between points
  40367. */
  40368. offset, canBeRegenerated, mesh,
  40369. /**
  40370. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40371. */
  40372. side) {
  40373. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40374. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40375. _this.pathArray = pathArray;
  40376. _this.closeArray = closeArray;
  40377. _this.closePath = closePath;
  40378. _this.offset = offset;
  40379. _this.side = side;
  40380. return _this;
  40381. }
  40382. /** @hidden */
  40383. RibbonGeometry.prototype._regenerateVertexData = function () {
  40384. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40385. };
  40386. RibbonGeometry.prototype.copy = function (id) {
  40387. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40388. };
  40389. return RibbonGeometry;
  40390. }(_PrimitiveGeometry));
  40391. BABYLON.RibbonGeometry = RibbonGeometry;
  40392. /**
  40393. * Creates a box geometry
  40394. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40395. */
  40396. var BoxGeometry = /** @class */ (function (_super) {
  40397. __extends(BoxGeometry, _super);
  40398. /**
  40399. * Creates a box geometry
  40400. * @param id defines the unique ID of the geometry
  40401. * @param scene defines the hosting scene
  40402. * @param size defines the zise of the box (width, height and depth are the same)
  40403. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40404. * @param mesh defines the hosting mesh (can be null)
  40405. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40406. */
  40407. function BoxGeometry(id, scene,
  40408. /**
  40409. * Defines the zise of the box (width, height and depth are the same)
  40410. */
  40411. size, canBeRegenerated, mesh,
  40412. /**
  40413. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40414. */
  40415. side) {
  40416. if (mesh === void 0) { mesh = null; }
  40417. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40418. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40419. _this.size = size;
  40420. _this.side = side;
  40421. return _this;
  40422. }
  40423. BoxGeometry.prototype._regenerateVertexData = function () {
  40424. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40425. };
  40426. BoxGeometry.prototype.copy = function (id) {
  40427. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40428. };
  40429. BoxGeometry.prototype.serialize = function () {
  40430. var serializationObject = _super.prototype.serialize.call(this);
  40431. serializationObject.size = this.size;
  40432. return serializationObject;
  40433. };
  40434. BoxGeometry.Parse = function (parsedBox, scene) {
  40435. if (scene.getGeometryByID(parsedBox.id)) {
  40436. return null; // null since geometry could be something else than a box...
  40437. }
  40438. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40439. if (BABYLON.Tags) {
  40440. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40441. }
  40442. scene.pushGeometry(box, true);
  40443. return box;
  40444. };
  40445. return BoxGeometry;
  40446. }(_PrimitiveGeometry));
  40447. BABYLON.BoxGeometry = BoxGeometry;
  40448. /**
  40449. * Creates a sphere geometry
  40450. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40451. */
  40452. var SphereGeometry = /** @class */ (function (_super) {
  40453. __extends(SphereGeometry, _super);
  40454. /**
  40455. * Create a new sphere geometry
  40456. * @param id defines the unique ID of the geometry
  40457. * @param scene defines the hosting scene
  40458. * @param segments defines the number of segments to use to create the sphere
  40459. * @param diameter defines the diameter of the sphere
  40460. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40461. * @param mesh defines the hosting mesh (can be null)
  40462. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40463. */
  40464. function SphereGeometry(id, scene,
  40465. /**
  40466. * Defines the number of segments to use to create the sphere
  40467. */
  40468. segments,
  40469. /**
  40470. * Defines the diameter of the sphere
  40471. */
  40472. diameter, canBeRegenerated, mesh,
  40473. /**
  40474. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40475. */
  40476. side) {
  40477. if (mesh === void 0) { mesh = null; }
  40478. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40479. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40480. _this.segments = segments;
  40481. _this.diameter = diameter;
  40482. _this.side = side;
  40483. return _this;
  40484. }
  40485. SphereGeometry.prototype._regenerateVertexData = function () {
  40486. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40487. };
  40488. SphereGeometry.prototype.copy = function (id) {
  40489. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40490. };
  40491. SphereGeometry.prototype.serialize = function () {
  40492. var serializationObject = _super.prototype.serialize.call(this);
  40493. serializationObject.segments = this.segments;
  40494. serializationObject.diameter = this.diameter;
  40495. return serializationObject;
  40496. };
  40497. SphereGeometry.Parse = function (parsedSphere, scene) {
  40498. if (scene.getGeometryByID(parsedSphere.id)) {
  40499. return null; // null since geometry could be something else than a sphere...
  40500. }
  40501. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40502. if (BABYLON.Tags) {
  40503. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40504. }
  40505. scene.pushGeometry(sphere, true);
  40506. return sphere;
  40507. };
  40508. return SphereGeometry;
  40509. }(_PrimitiveGeometry));
  40510. BABYLON.SphereGeometry = SphereGeometry;
  40511. /**
  40512. * Creates a disc geometry
  40513. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40514. */
  40515. var DiscGeometry = /** @class */ (function (_super) {
  40516. __extends(DiscGeometry, _super);
  40517. /**
  40518. * Creates a new disc geometry
  40519. * @param id defines the unique ID of the geometry
  40520. * @param scene defines the hosting scene
  40521. * @param radius defines the radius of the disc
  40522. * @param tessellation defines the tesselation factor to apply to the disc
  40523. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40524. * @param mesh defines the hosting mesh (can be null)
  40525. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. function DiscGeometry(id, scene,
  40528. /**
  40529. * Defines the radius of the disc
  40530. */
  40531. radius,
  40532. /**
  40533. * Defines the tesselation factor to apply to the disc
  40534. */
  40535. tessellation, canBeRegenerated, mesh,
  40536. /**
  40537. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40538. */
  40539. side) {
  40540. if (mesh === void 0) { mesh = null; }
  40541. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40542. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40543. _this.radius = radius;
  40544. _this.tessellation = tessellation;
  40545. _this.side = side;
  40546. return _this;
  40547. }
  40548. DiscGeometry.prototype._regenerateVertexData = function () {
  40549. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40550. };
  40551. DiscGeometry.prototype.copy = function (id) {
  40552. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40553. };
  40554. return DiscGeometry;
  40555. }(_PrimitiveGeometry));
  40556. BABYLON.DiscGeometry = DiscGeometry;
  40557. /**
  40558. * Creates a new cylinder geometry
  40559. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40560. */
  40561. var CylinderGeometry = /** @class */ (function (_super) {
  40562. __extends(CylinderGeometry, _super);
  40563. /**
  40564. * Creates a new cylinder geometry
  40565. * @param id defines the unique ID of the geometry
  40566. * @param scene defines the hosting scene
  40567. * @param height defines the height of the cylinder
  40568. * @param diameterTop defines the diameter of the cylinder's top cap
  40569. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40570. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40571. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40572. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40573. * @param mesh defines the hosting mesh (can be null)
  40574. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40575. */
  40576. function CylinderGeometry(id, scene,
  40577. /**
  40578. * Defines the height of the cylinder
  40579. */
  40580. height,
  40581. /**
  40582. * Defines the diameter of the cylinder's top cap
  40583. */
  40584. diameterTop,
  40585. /**
  40586. * Defines the diameter of the cylinder's bottom cap
  40587. */
  40588. diameterBottom,
  40589. /**
  40590. * Defines the tessellation factor to apply to the cylinder
  40591. */
  40592. tessellation,
  40593. /**
  40594. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40595. */
  40596. subdivisions, canBeRegenerated, mesh,
  40597. /**
  40598. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40599. */
  40600. side) {
  40601. if (subdivisions === void 0) { subdivisions = 1; }
  40602. if (mesh === void 0) { mesh = null; }
  40603. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40604. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40605. _this.height = height;
  40606. _this.diameterTop = diameterTop;
  40607. _this.diameterBottom = diameterBottom;
  40608. _this.tessellation = tessellation;
  40609. _this.subdivisions = subdivisions;
  40610. _this.side = side;
  40611. return _this;
  40612. }
  40613. CylinderGeometry.prototype._regenerateVertexData = function () {
  40614. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40615. };
  40616. CylinderGeometry.prototype.copy = function (id) {
  40617. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40618. };
  40619. CylinderGeometry.prototype.serialize = function () {
  40620. var serializationObject = _super.prototype.serialize.call(this);
  40621. serializationObject.height = this.height;
  40622. serializationObject.diameterTop = this.diameterTop;
  40623. serializationObject.diameterBottom = this.diameterBottom;
  40624. serializationObject.tessellation = this.tessellation;
  40625. return serializationObject;
  40626. };
  40627. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40628. if (scene.getGeometryByID(parsedCylinder.id)) {
  40629. return null; // null since geometry could be something else than a cylinder...
  40630. }
  40631. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40632. if (BABYLON.Tags) {
  40633. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40634. }
  40635. scene.pushGeometry(cylinder, true);
  40636. return cylinder;
  40637. };
  40638. return CylinderGeometry;
  40639. }(_PrimitiveGeometry));
  40640. BABYLON.CylinderGeometry = CylinderGeometry;
  40641. /**
  40642. * Creates a new torus geometry
  40643. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40644. */
  40645. var TorusGeometry = /** @class */ (function (_super) {
  40646. __extends(TorusGeometry, _super);
  40647. /**
  40648. * Creates a new torus geometry
  40649. * @param id defines the unique ID of the geometry
  40650. * @param scene defines the hosting scene
  40651. * @param diameter defines the diameter of the torus
  40652. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40653. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40654. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40655. * @param mesh defines the hosting mesh (can be null)
  40656. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40657. */
  40658. function TorusGeometry(id, scene,
  40659. /**
  40660. * Defines the diameter of the torus
  40661. */
  40662. diameter,
  40663. /**
  40664. * Defines the thickness of the torus (ie. internal diameter)
  40665. */
  40666. thickness,
  40667. /**
  40668. * Defines the tesselation factor to apply to the torus
  40669. */
  40670. tessellation, canBeRegenerated, mesh,
  40671. /**
  40672. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40673. */
  40674. side) {
  40675. if (mesh === void 0) { mesh = null; }
  40676. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40677. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40678. _this.diameter = diameter;
  40679. _this.thickness = thickness;
  40680. _this.tessellation = tessellation;
  40681. _this.side = side;
  40682. return _this;
  40683. }
  40684. TorusGeometry.prototype._regenerateVertexData = function () {
  40685. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40686. };
  40687. TorusGeometry.prototype.copy = function (id) {
  40688. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40689. };
  40690. TorusGeometry.prototype.serialize = function () {
  40691. var serializationObject = _super.prototype.serialize.call(this);
  40692. serializationObject.diameter = this.diameter;
  40693. serializationObject.thickness = this.thickness;
  40694. serializationObject.tessellation = this.tessellation;
  40695. return serializationObject;
  40696. };
  40697. TorusGeometry.Parse = function (parsedTorus, scene) {
  40698. if (scene.getGeometryByID(parsedTorus.id)) {
  40699. return null; // null since geometry could be something else than a torus...
  40700. }
  40701. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40702. if (BABYLON.Tags) {
  40703. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40704. }
  40705. scene.pushGeometry(torus, true);
  40706. return torus;
  40707. };
  40708. return TorusGeometry;
  40709. }(_PrimitiveGeometry));
  40710. BABYLON.TorusGeometry = TorusGeometry;
  40711. /**
  40712. * Creates a new ground geometry
  40713. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40714. */
  40715. var GroundGeometry = /** @class */ (function (_super) {
  40716. __extends(GroundGeometry, _super);
  40717. /**
  40718. * Creates a new ground geometry
  40719. * @param id defines the unique ID of the geometry
  40720. * @param scene defines the hosting scene
  40721. * @param width defines the width of the ground
  40722. * @param height defines the height of the ground
  40723. * @param subdivisions defines the subdivisions to apply to the ground
  40724. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40725. * @param mesh defines the hosting mesh (can be null)
  40726. */
  40727. function GroundGeometry(id, scene,
  40728. /**
  40729. * Defines the width of the ground
  40730. */
  40731. width,
  40732. /**
  40733. * Defines the height of the ground
  40734. */
  40735. height,
  40736. /**
  40737. * Defines the subdivisions to apply to the ground
  40738. */
  40739. subdivisions, canBeRegenerated, mesh) {
  40740. if (mesh === void 0) { mesh = null; }
  40741. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40742. _this.width = width;
  40743. _this.height = height;
  40744. _this.subdivisions = subdivisions;
  40745. return _this;
  40746. }
  40747. GroundGeometry.prototype._regenerateVertexData = function () {
  40748. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40749. };
  40750. GroundGeometry.prototype.copy = function (id) {
  40751. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40752. };
  40753. GroundGeometry.prototype.serialize = function () {
  40754. var serializationObject = _super.prototype.serialize.call(this);
  40755. serializationObject.width = this.width;
  40756. serializationObject.height = this.height;
  40757. serializationObject.subdivisions = this.subdivisions;
  40758. return serializationObject;
  40759. };
  40760. GroundGeometry.Parse = function (parsedGround, scene) {
  40761. if (scene.getGeometryByID(parsedGround.id)) {
  40762. return null; // null since geometry could be something else than a ground...
  40763. }
  40764. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40765. if (BABYLON.Tags) {
  40766. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40767. }
  40768. scene.pushGeometry(ground, true);
  40769. return ground;
  40770. };
  40771. return GroundGeometry;
  40772. }(_PrimitiveGeometry));
  40773. BABYLON.GroundGeometry = GroundGeometry;
  40774. /**
  40775. * Creates a tiled ground geometry
  40776. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40777. */
  40778. var TiledGroundGeometry = /** @class */ (function (_super) {
  40779. __extends(TiledGroundGeometry, _super);
  40780. /**
  40781. * Creates a tiled ground geometry
  40782. * @param id defines the unique ID of the geometry
  40783. * @param scene defines the hosting scene
  40784. * @param xmin defines the minimum value on X axis
  40785. * @param zmin defines the minimum value on Z axis
  40786. * @param xmax defines the maximum value on X axis
  40787. * @param zmax defines the maximum value on Z axis
  40788. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40789. * @param precision defines the precision to use when computing the tiles
  40790. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40791. * @param mesh defines the hosting mesh (can be null)
  40792. */
  40793. function TiledGroundGeometry(id, scene,
  40794. /**
  40795. * Defines the minimum value on X axis
  40796. */
  40797. xmin,
  40798. /**
  40799. * Defines the minimum value on Z axis
  40800. */
  40801. zmin,
  40802. /**
  40803. * Defines the maximum value on X axis
  40804. */
  40805. xmax,
  40806. /**
  40807. * Defines the maximum value on Z axis
  40808. */
  40809. zmax,
  40810. /**
  40811. * Defines the subdivisions to apply to the ground
  40812. */
  40813. subdivisions,
  40814. /**
  40815. * Defines the precision to use when computing the tiles
  40816. */
  40817. precision, canBeRegenerated, mesh) {
  40818. if (mesh === void 0) { mesh = null; }
  40819. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40820. _this.xmin = xmin;
  40821. _this.zmin = zmin;
  40822. _this.xmax = xmax;
  40823. _this.zmax = zmax;
  40824. _this.subdivisions = subdivisions;
  40825. _this.precision = precision;
  40826. return _this;
  40827. }
  40828. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40829. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40830. };
  40831. TiledGroundGeometry.prototype.copy = function (id) {
  40832. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40833. };
  40834. return TiledGroundGeometry;
  40835. }(_PrimitiveGeometry));
  40836. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40837. /**
  40838. * Creates a plane geometry
  40839. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40840. */
  40841. var PlaneGeometry = /** @class */ (function (_super) {
  40842. __extends(PlaneGeometry, _super);
  40843. /**
  40844. * Creates a plane geometry
  40845. * @param id defines the unique ID of the geometry
  40846. * @param scene defines the hosting scene
  40847. * @param size defines the size of the plane (width === height)
  40848. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40849. * @param mesh defines the hosting mesh (can be null)
  40850. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40851. */
  40852. function PlaneGeometry(id, scene,
  40853. /**
  40854. * Defines the size of the plane (width === height)
  40855. */
  40856. size, canBeRegenerated, mesh,
  40857. /**
  40858. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40859. */
  40860. side) {
  40861. if (mesh === void 0) { mesh = null; }
  40862. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40863. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40864. _this.size = size;
  40865. _this.side = side;
  40866. return _this;
  40867. }
  40868. PlaneGeometry.prototype._regenerateVertexData = function () {
  40869. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40870. };
  40871. PlaneGeometry.prototype.copy = function (id) {
  40872. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40873. };
  40874. PlaneGeometry.prototype.serialize = function () {
  40875. var serializationObject = _super.prototype.serialize.call(this);
  40876. serializationObject.size = this.size;
  40877. return serializationObject;
  40878. };
  40879. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40880. if (scene.getGeometryByID(parsedPlane.id)) {
  40881. return null; // null since geometry could be something else than a ground...
  40882. }
  40883. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40884. if (BABYLON.Tags) {
  40885. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40886. }
  40887. scene.pushGeometry(plane, true);
  40888. return plane;
  40889. };
  40890. return PlaneGeometry;
  40891. }(_PrimitiveGeometry));
  40892. BABYLON.PlaneGeometry = PlaneGeometry;
  40893. /**
  40894. * Creates a torus knot geometry
  40895. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40896. */
  40897. var TorusKnotGeometry = /** @class */ (function (_super) {
  40898. __extends(TorusKnotGeometry, _super);
  40899. /**
  40900. * Creates a torus knot geometry
  40901. * @param id defines the unique ID of the geometry
  40902. * @param scene defines the hosting scene
  40903. * @param radius defines the radius of the torus knot
  40904. * @param tube defines the thickness of the torus knot tube
  40905. * @param radialSegments defines the number of radial segments
  40906. * @param tubularSegments defines the number of tubular segments
  40907. * @param p defines the first number of windings
  40908. * @param q defines the second number of windings
  40909. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40910. * @param mesh defines the hosting mesh (can be null)
  40911. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40912. */
  40913. function TorusKnotGeometry(id, scene,
  40914. /**
  40915. * Defines the radius of the torus knot
  40916. */
  40917. radius,
  40918. /**
  40919. * Defines the thickness of the torus knot tube
  40920. */
  40921. tube,
  40922. /**
  40923. * Defines the number of radial segments
  40924. */
  40925. radialSegments,
  40926. /**
  40927. * Defines the number of tubular segments
  40928. */
  40929. tubularSegments,
  40930. /**
  40931. * Defines the first number of windings
  40932. */
  40933. p,
  40934. /**
  40935. * Defines the second number of windings
  40936. */
  40937. q, canBeRegenerated, mesh,
  40938. /**
  40939. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40940. */
  40941. side) {
  40942. if (mesh === void 0) { mesh = null; }
  40943. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40944. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40945. _this.radius = radius;
  40946. _this.tube = tube;
  40947. _this.radialSegments = radialSegments;
  40948. _this.tubularSegments = tubularSegments;
  40949. _this.p = p;
  40950. _this.q = q;
  40951. _this.side = side;
  40952. return _this;
  40953. }
  40954. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40955. 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 });
  40956. };
  40957. TorusKnotGeometry.prototype.copy = function (id) {
  40958. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40959. };
  40960. TorusKnotGeometry.prototype.serialize = function () {
  40961. var serializationObject = _super.prototype.serialize.call(this);
  40962. serializationObject.radius = this.radius;
  40963. serializationObject.tube = this.tube;
  40964. serializationObject.radialSegments = this.radialSegments;
  40965. serializationObject.tubularSegments = this.tubularSegments;
  40966. serializationObject.p = this.p;
  40967. serializationObject.q = this.q;
  40968. return serializationObject;
  40969. };
  40970. ;
  40971. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40972. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40973. return null; // null since geometry could be something else than a ground...
  40974. }
  40975. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40976. if (BABYLON.Tags) {
  40977. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40978. }
  40979. scene.pushGeometry(torusKnot, true);
  40980. return torusKnot;
  40981. };
  40982. return TorusKnotGeometry;
  40983. }(_PrimitiveGeometry));
  40984. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40985. //}
  40986. })(BABYLON || (BABYLON = {}));
  40987. //# sourceMappingURL=babylon.geometry.js.map
  40988. var BABYLON;
  40989. (function (BABYLON) {
  40990. /**
  40991. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40992. */
  40993. var PerformanceMonitor = /** @class */ (function () {
  40994. /**
  40995. * constructor
  40996. * @param frameSampleSize The number of samples required to saturate the sliding window
  40997. */
  40998. function PerformanceMonitor(frameSampleSize) {
  40999. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41000. this._enabled = true;
  41001. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41002. }
  41003. /**
  41004. * Samples current frame
  41005. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41006. */
  41007. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41008. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41009. if (!this._enabled)
  41010. return;
  41011. if (this._lastFrameTimeMs != null) {
  41012. var dt = timeMs - this._lastFrameTimeMs;
  41013. this._rollingFrameTime.add(dt);
  41014. }
  41015. this._lastFrameTimeMs = timeMs;
  41016. };
  41017. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41018. /**
  41019. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41020. * @return Average frame time in milliseconds
  41021. */
  41022. get: function () {
  41023. return this._rollingFrameTime.average;
  41024. },
  41025. enumerable: true,
  41026. configurable: true
  41027. });
  41028. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41029. /**
  41030. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41031. * @return Frame time variance in milliseconds squared
  41032. */
  41033. get: function () {
  41034. return this._rollingFrameTime.variance;
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41040. /**
  41041. * Returns the frame time of the most recent frame
  41042. * @return Frame time in milliseconds
  41043. */
  41044. get: function () {
  41045. return this._rollingFrameTime.history(0);
  41046. },
  41047. enumerable: true,
  41048. configurable: true
  41049. });
  41050. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41051. /**
  41052. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41053. * @return Framerate in frames per second
  41054. */
  41055. get: function () {
  41056. return 1000.0 / this._rollingFrameTime.average;
  41057. },
  41058. enumerable: true,
  41059. configurable: true
  41060. });
  41061. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41062. /**
  41063. * Returns the average framerate in frames per second using the most recent frame time
  41064. * @return Framerate in frames per second
  41065. */
  41066. get: function () {
  41067. var history = this._rollingFrameTime.history(0);
  41068. if (history === 0) {
  41069. return 0;
  41070. }
  41071. return 1000.0 / history;
  41072. },
  41073. enumerable: true,
  41074. configurable: true
  41075. });
  41076. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41077. /**
  41078. * Returns true if enough samples have been taken to completely fill the sliding window
  41079. * @return true if saturated
  41080. */
  41081. get: function () {
  41082. return this._rollingFrameTime.isSaturated();
  41083. },
  41084. enumerable: true,
  41085. configurable: true
  41086. });
  41087. /**
  41088. * Enables contributions to the sliding window sample set
  41089. */
  41090. PerformanceMonitor.prototype.enable = function () {
  41091. this._enabled = true;
  41092. };
  41093. /**
  41094. * Disables contributions to the sliding window sample set
  41095. * Samples will not be interpolated over the disabled period
  41096. */
  41097. PerformanceMonitor.prototype.disable = function () {
  41098. this._enabled = false;
  41099. //clear last sample to avoid interpolating over the disabled period when next enabled
  41100. this._lastFrameTimeMs = null;
  41101. };
  41102. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41103. /**
  41104. * Returns true if sampling is enabled
  41105. * @return true if enabled
  41106. */
  41107. get: function () {
  41108. return this._enabled;
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. /**
  41114. * Resets performance monitor
  41115. */
  41116. PerformanceMonitor.prototype.reset = function () {
  41117. //clear last sample to avoid interpolating over the disabled period when next enabled
  41118. this._lastFrameTimeMs = null;
  41119. //wipe record
  41120. this._rollingFrameTime.reset();
  41121. };
  41122. return PerformanceMonitor;
  41123. }());
  41124. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41125. /**
  41126. * RollingAverage
  41127. *
  41128. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41129. */
  41130. var RollingAverage = /** @class */ (function () {
  41131. /**
  41132. * constructor
  41133. * @param length The number of samples required to saturate the sliding window
  41134. */
  41135. function RollingAverage(length) {
  41136. this._samples = new Array(length);
  41137. this.reset();
  41138. }
  41139. /**
  41140. * Adds a sample to the sample set
  41141. * @param v The sample value
  41142. */
  41143. RollingAverage.prototype.add = function (v) {
  41144. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41145. var delta;
  41146. //we need to check if we've already wrapped round
  41147. if (this.isSaturated()) {
  41148. //remove bottom of stack from mean
  41149. var bottomValue = this._samples[this._pos];
  41150. delta = bottomValue - this.average;
  41151. this.average -= delta / (this._sampleCount - 1);
  41152. this._m2 -= delta * (bottomValue - this.average);
  41153. }
  41154. else {
  41155. this._sampleCount++;
  41156. }
  41157. //add new value to mean
  41158. delta = v - this.average;
  41159. this.average += delta / (this._sampleCount);
  41160. this._m2 += delta * (v - this.average);
  41161. //set the new variance
  41162. this.variance = this._m2 / (this._sampleCount - 1);
  41163. this._samples[this._pos] = v;
  41164. this._pos++;
  41165. this._pos %= this._samples.length; //positive wrap around
  41166. };
  41167. /**
  41168. * Returns previously added values or null if outside of history or outside the sliding window domain
  41169. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41170. * @return Value previously recorded with add() or null if outside of range
  41171. */
  41172. RollingAverage.prototype.history = function (i) {
  41173. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41174. return 0;
  41175. }
  41176. var i0 = this._wrapPosition(this._pos - 1.0);
  41177. return this._samples[this._wrapPosition(i0 - i)];
  41178. };
  41179. /**
  41180. * Returns true if enough samples have been taken to completely fill the sliding window
  41181. * @return true if sample-set saturated
  41182. */
  41183. RollingAverage.prototype.isSaturated = function () {
  41184. return this._sampleCount >= this._samples.length;
  41185. };
  41186. /**
  41187. * Resets the rolling average (equivalent to 0 samples taken so far)
  41188. */
  41189. RollingAverage.prototype.reset = function () {
  41190. this.average = 0;
  41191. this.variance = 0;
  41192. this._sampleCount = 0;
  41193. this._pos = 0;
  41194. this._m2 = 0;
  41195. };
  41196. /**
  41197. * Wraps a value around the sample range boundaries
  41198. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41199. * @return Wrapped position in sample range
  41200. */
  41201. RollingAverage.prototype._wrapPosition = function (i) {
  41202. var max = this._samples.length;
  41203. return ((i % max) + max) % max;
  41204. };
  41205. return RollingAverage;
  41206. }());
  41207. BABYLON.RollingAverage = RollingAverage;
  41208. })(BABYLON || (BABYLON = {}));
  41209. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41210. var BABYLON;
  41211. (function (BABYLON) {
  41212. /**
  41213. * "Static Class" containing the most commonly used helper while dealing with material for
  41214. * rendering purpose.
  41215. *
  41216. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41217. *
  41218. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41219. */
  41220. var MaterialHelper = /** @class */ (function () {
  41221. function MaterialHelper() {
  41222. }
  41223. /**
  41224. * Bind the current view position to an effect.
  41225. * @param effect The effect to be bound
  41226. * @param scene The scene the eyes position is used from
  41227. */
  41228. MaterialHelper.BindEyePosition = function (effect, scene) {
  41229. if (scene._forcedViewPosition) {
  41230. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41231. return;
  41232. }
  41233. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41234. };
  41235. /**
  41236. * Helps preparing the defines values about the UVs in used in the effect.
  41237. * UVs are shared as much as we can accross chanels in the shaders.
  41238. * @param texture The texture we are preparing the UVs for
  41239. * @param defines The defines to update
  41240. * @param key The chanel key "diffuse", "specular"... used in the shader
  41241. */
  41242. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41243. defines._needUVs = true;
  41244. defines[key] = true;
  41245. if (texture.getTextureMatrix().isIdentity(true)) {
  41246. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41247. if (texture.coordinatesIndex === 0) {
  41248. defines["MAINUV1"] = true;
  41249. }
  41250. else {
  41251. defines["MAINUV2"] = true;
  41252. }
  41253. }
  41254. else {
  41255. defines[key + "DIRECTUV"] = 0;
  41256. }
  41257. };
  41258. /**
  41259. * Binds a texture matrix value to its corrsponding uniform
  41260. * @param texture The texture to bind the matrix for
  41261. * @param uniformBuffer The uniform buffer receivin the data
  41262. * @param key The chanel key "diffuse", "specular"... used in the shader
  41263. */
  41264. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41265. var matrix = texture.getTextureMatrix();
  41266. if (!matrix.isIdentity(true)) {
  41267. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41268. }
  41269. };
  41270. /**
  41271. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41272. * @param mesh defines the current mesh
  41273. * @param scene defines the current scene
  41274. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41275. * @param pointsCloud defines if point cloud rendering has to be turned on
  41276. * @param fogEnabled defines if fog has to be turned on
  41277. * @param alphaTest defines if alpha testing has to be turned on
  41278. * @param defines defines the current list of defines
  41279. */
  41280. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41281. if (defines._areMiscDirty) {
  41282. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41283. defines["POINTSIZE"] = pointsCloud;
  41284. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41285. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41286. defines["ALPHATEST"] = alphaTest;
  41287. }
  41288. };
  41289. /**
  41290. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41291. * @param scene defines the current scene
  41292. * @param engine defines the current engine
  41293. * @param defines specifies the list of active defines
  41294. * @param useInstances defines if instances have to be turned on
  41295. * @param useClipPlane defines if clip plane have to be turned on
  41296. */
  41297. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41298. if (useClipPlane === void 0) { useClipPlane = null; }
  41299. var changed = false;
  41300. if (useClipPlane == null) {
  41301. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41302. }
  41303. if (defines["CLIPPLANE"] !== useClipPlane) {
  41304. defines["CLIPPLANE"] = useClipPlane;
  41305. changed = true;
  41306. }
  41307. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41308. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41309. changed = true;
  41310. }
  41311. if (defines["INSTANCES"] !== useInstances) {
  41312. defines["INSTANCES"] = useInstances;
  41313. changed = true;
  41314. }
  41315. if (changed) {
  41316. defines.markAsUnprocessed();
  41317. }
  41318. };
  41319. /**
  41320. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41321. * @param mesh The mesh containing the geometry data we will draw
  41322. * @param defines The defines to update
  41323. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41324. * @param useBones Precise whether bones should be used or not (override mesh info)
  41325. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41326. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41327. * @returns false if defines are considered not dirty and have not been checked
  41328. */
  41329. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41330. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41331. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41332. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41333. return false;
  41334. }
  41335. defines._normals = defines._needNormals;
  41336. defines._uvs = defines._needUVs;
  41337. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41338. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41339. defines["TANGENT"] = true;
  41340. }
  41341. if (defines._needUVs) {
  41342. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41343. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41344. }
  41345. else {
  41346. defines["UV1"] = false;
  41347. defines["UV2"] = false;
  41348. }
  41349. if (useVertexColor) {
  41350. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41351. defines["VERTEXCOLOR"] = hasVertexColors;
  41352. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41353. }
  41354. if (useBones) {
  41355. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41356. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41357. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41358. }
  41359. else {
  41360. defines["NUM_BONE_INFLUENCERS"] = 0;
  41361. defines["BonesPerMesh"] = 0;
  41362. }
  41363. }
  41364. if (useMorphTargets) {
  41365. var manager = mesh.morphTargetManager;
  41366. if (manager) {
  41367. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41368. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41369. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41370. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41371. }
  41372. else {
  41373. defines["MORPHTARGETS_TANGENT"] = false;
  41374. defines["MORPHTARGETS_NORMAL"] = false;
  41375. defines["MORPHTARGETS"] = false;
  41376. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41377. }
  41378. }
  41379. return true;
  41380. };
  41381. /**
  41382. * Prepares the defines related to the light information passed in parameter
  41383. * @param scene The scene we are intending to draw
  41384. * @param mesh The mesh the effect is compiling for
  41385. * @param defines The defines to update
  41386. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41387. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41388. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41389. * @returns true if normals will be required for the rest of the effect
  41390. */
  41391. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41392. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41393. if (disableLighting === void 0) { disableLighting = false; }
  41394. if (!defines._areLightsDirty) {
  41395. return defines._needNormals;
  41396. }
  41397. var lightIndex = 0;
  41398. var needNormals = false;
  41399. var needRebuild = false;
  41400. var lightmapMode = false;
  41401. var shadowEnabled = false;
  41402. var specularEnabled = false;
  41403. if (scene.lightsEnabled && !disableLighting) {
  41404. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41405. var light = _a[_i];
  41406. needNormals = true;
  41407. if (defines["LIGHT" + lightIndex] === undefined) {
  41408. needRebuild = true;
  41409. }
  41410. defines["LIGHT" + lightIndex] = true;
  41411. defines["SPOTLIGHT" + lightIndex] = false;
  41412. defines["HEMILIGHT" + lightIndex] = false;
  41413. defines["POINTLIGHT" + lightIndex] = false;
  41414. defines["DIRLIGHT" + lightIndex] = false;
  41415. var type;
  41416. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41417. type = "SPOTLIGHT" + lightIndex;
  41418. var spotLight = light;
  41419. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41420. }
  41421. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41422. type = "HEMILIGHT" + lightIndex;
  41423. }
  41424. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41425. type = "POINTLIGHT" + lightIndex;
  41426. }
  41427. else {
  41428. type = "DIRLIGHT" + lightIndex;
  41429. }
  41430. defines[type] = true;
  41431. // Specular
  41432. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41433. specularEnabled = true;
  41434. }
  41435. // Shadows
  41436. defines["SHADOW" + lightIndex] = false;
  41437. defines["SHADOWPCF" + lightIndex] = false;
  41438. defines["SHADOWPCSS" + lightIndex] = false;
  41439. defines["SHADOWPOISSON" + lightIndex] = false;
  41440. defines["SHADOWESM" + lightIndex] = false;
  41441. defines["SHADOWCUBE" + lightIndex] = false;
  41442. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41443. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41444. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41445. var shadowGenerator = light.getShadowGenerator();
  41446. if (shadowGenerator) {
  41447. shadowEnabled = true;
  41448. shadowGenerator.prepareDefines(defines, lightIndex);
  41449. }
  41450. }
  41451. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41452. lightmapMode = true;
  41453. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41454. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41455. }
  41456. else {
  41457. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41458. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41459. }
  41460. lightIndex++;
  41461. if (lightIndex === maxSimultaneousLights)
  41462. break;
  41463. }
  41464. }
  41465. defines["SPECULARTERM"] = specularEnabled;
  41466. defines["SHADOWS"] = shadowEnabled;
  41467. // Resetting all other lights if any
  41468. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41469. if (defines["LIGHT" + index] !== undefined) {
  41470. defines["LIGHT" + index] = false;
  41471. defines["HEMILIGHT" + lightIndex] = false;
  41472. defines["POINTLIGHT" + lightIndex] = false;
  41473. defines["DIRLIGHT" + lightIndex] = false;
  41474. defines["SPOTLIGHT" + lightIndex] = false;
  41475. defines["SHADOW" + lightIndex] = false;
  41476. }
  41477. }
  41478. var caps = scene.getEngine().getCaps();
  41479. if (defines["SHADOWFLOAT"] === undefined) {
  41480. needRebuild = true;
  41481. }
  41482. defines["SHADOWFLOAT"] = shadowEnabled &&
  41483. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41484. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41485. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41486. if (needRebuild) {
  41487. defines.rebuild();
  41488. }
  41489. return needNormals;
  41490. };
  41491. /**
  41492. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41493. * that won t be acctive due to defines being turned off.
  41494. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41495. * @param samplersList The samplers list
  41496. * @param defines The defines helping in the list generation
  41497. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41498. */
  41499. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41500. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41501. var uniformsList;
  41502. var uniformBuffersList = null;
  41503. if (uniformsListOrOptions.uniformsNames) {
  41504. var options = uniformsListOrOptions;
  41505. uniformsList = options.uniformsNames;
  41506. uniformBuffersList = options.uniformBuffersNames;
  41507. samplersList = options.samplers;
  41508. defines = options.defines;
  41509. maxSimultaneousLights = options.maxSimultaneousLights;
  41510. }
  41511. else {
  41512. uniformsList = uniformsListOrOptions;
  41513. if (!samplersList) {
  41514. samplersList = [];
  41515. }
  41516. }
  41517. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41518. if (!defines["LIGHT" + lightIndex]) {
  41519. break;
  41520. }
  41521. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41522. if (uniformBuffersList) {
  41523. uniformBuffersList.push("Light" + lightIndex);
  41524. }
  41525. samplersList.push("shadowSampler" + lightIndex);
  41526. samplersList.push("depthSampler" + lightIndex);
  41527. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41528. samplersList.push("projectionLightSampler" + lightIndex);
  41529. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41530. }
  41531. }
  41532. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41533. uniformsList.push("morphTargetInfluences");
  41534. }
  41535. };
  41536. /**
  41537. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41538. * @param defines The defines to update while falling back
  41539. * @param fallbacks The authorized effect fallbacks
  41540. * @param maxSimultaneousLights The maximum number of lights allowed
  41541. * @param rank the current rank of the Effect
  41542. * @returns The newly affected rank
  41543. */
  41544. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41545. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41546. if (rank === void 0) { rank = 0; }
  41547. var lightFallbackRank = 0;
  41548. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41549. if (!defines["LIGHT" + lightIndex]) {
  41550. break;
  41551. }
  41552. if (lightIndex > 0) {
  41553. lightFallbackRank = rank + lightIndex;
  41554. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41555. }
  41556. if (!defines["SHADOWS"]) {
  41557. if (defines["SHADOW" + lightIndex]) {
  41558. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41559. }
  41560. if (defines["SHADOWPCF" + lightIndex]) {
  41561. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41562. }
  41563. if (defines["SHADOWPCSS" + lightIndex]) {
  41564. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41565. }
  41566. if (defines["SHADOWPOISSON" + lightIndex]) {
  41567. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41568. }
  41569. if (defines["SHADOWESM" + lightIndex]) {
  41570. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41571. }
  41572. }
  41573. }
  41574. return lightFallbackRank++;
  41575. };
  41576. /**
  41577. * Prepares the list of attributes required for morph targets according to the effect defines.
  41578. * @param attribs The current list of supported attribs
  41579. * @param mesh The mesh to prepare the morph targets attributes for
  41580. * @param defines The current Defines of the effect
  41581. */
  41582. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41583. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41584. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41585. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41586. var manager = mesh.morphTargetManager;
  41587. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41588. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41589. for (var index = 0; index < influencers; index++) {
  41590. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41591. if (normal) {
  41592. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41593. }
  41594. if (tangent) {
  41595. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41596. }
  41597. if (attribs.length > maxAttributesCount) {
  41598. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41599. }
  41600. }
  41601. }
  41602. };
  41603. /**
  41604. * Prepares the list of attributes required for bones according to the effect defines.
  41605. * @param attribs The current list of supported attribs
  41606. * @param mesh The mesh to prepare the bones attributes for
  41607. * @param defines The current Defines of the effect
  41608. * @param fallbacks The current efffect fallback strategy
  41609. */
  41610. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41611. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41612. fallbacks.addCPUSkinningFallback(0, mesh);
  41613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41615. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41616. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41617. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41618. }
  41619. }
  41620. };
  41621. /**
  41622. * Prepares the list of attributes required for instances according to the effect defines.
  41623. * @param attribs The current list of supported attribs
  41624. * @param defines The current Defines of the effect
  41625. */
  41626. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41627. if (defines["INSTANCES"]) {
  41628. attribs.push("world0");
  41629. attribs.push("world1");
  41630. attribs.push("world2");
  41631. attribs.push("world3");
  41632. }
  41633. };
  41634. /**
  41635. * Binds the light shadow information to the effect for the given mesh.
  41636. * @param light The light containing the generator
  41637. * @param scene The scene the lights belongs to
  41638. * @param mesh The mesh we are binding the information to render
  41639. * @param lightIndex The light index in the effect used to render the mesh
  41640. * @param effect The effect we are binding the data to
  41641. */
  41642. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41643. if (light.shadowEnabled && mesh.receiveShadows) {
  41644. var shadowGenerator = light.getShadowGenerator();
  41645. if (shadowGenerator) {
  41646. shadowGenerator.bindShadowLight(lightIndex, effect);
  41647. }
  41648. }
  41649. };
  41650. /**
  41651. * Binds the light information to the effect.
  41652. * @param light The light containing the generator
  41653. * @param effect The effect we are binding the data to
  41654. * @param lightIndex The light index in the effect used to render
  41655. */
  41656. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41657. light.transferToEffect(effect, lightIndex + "");
  41658. };
  41659. /**
  41660. * Binds the lights information from the scene to the effect for the given mesh.
  41661. * @param scene The scene the lights belongs to
  41662. * @param mesh The mesh we are binding the information to render
  41663. * @param effect The effect we are binding the data to
  41664. * @param defines The generated defines for the effect
  41665. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41666. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41667. */
  41668. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41669. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41670. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41671. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41672. for (var i = 0; i < len; i++) {
  41673. var light = mesh._lightSources[i];
  41674. var iAsString = i.toString();
  41675. var scaledIntensity = light.getScaledIntensity();
  41676. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41677. MaterialHelper.BindLightProperties(light, effect, i);
  41678. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41679. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41680. if (defines["SPECULARTERM"]) {
  41681. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41682. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41683. }
  41684. // Shadows
  41685. if (scene.shadowsEnabled) {
  41686. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41687. }
  41688. light._uniformBuffer.update();
  41689. }
  41690. };
  41691. /**
  41692. * Binds the fog information from the scene to the effect for the given mesh.
  41693. * @param scene The scene the lights belongs to
  41694. * @param mesh The mesh we are binding the information to render
  41695. * @param effect The effect we are binding the data to
  41696. */
  41697. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41698. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41699. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41700. effect.setColor3("vFogColor", scene.fogColor);
  41701. }
  41702. };
  41703. /**
  41704. * Binds the bones information from the mesh to the effect.
  41705. * @param mesh The mesh we are binding the information to render
  41706. * @param effect The effect we are binding the data to
  41707. */
  41708. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41709. if (!effect || !mesh) {
  41710. return;
  41711. }
  41712. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41713. mesh.computeBonesUsingShaders = false;
  41714. }
  41715. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41716. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41717. if (matrices) {
  41718. effect.setMatrices("mBones", matrices);
  41719. }
  41720. }
  41721. };
  41722. /**
  41723. * Binds the morph targets information from the mesh to the effect.
  41724. * @param abstractMesh The mesh we are binding the information to render
  41725. * @param effect The effect we are binding the data to
  41726. */
  41727. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41728. var manager = abstractMesh.morphTargetManager;
  41729. if (!abstractMesh || !manager) {
  41730. return;
  41731. }
  41732. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41733. };
  41734. /**
  41735. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41736. * @param defines The generated defines used in the effect
  41737. * @param effect The effect we are binding the data to
  41738. * @param scene The scene we are willing to render with logarithmic scale for
  41739. */
  41740. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41741. if (defines["LOGARITHMICDEPTH"]) {
  41742. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41743. }
  41744. };
  41745. /**
  41746. * Binds the clip plane information from the scene to the effect.
  41747. * @param scene The scene the clip plane information are extracted from
  41748. * @param effect The effect we are binding the data to
  41749. */
  41750. MaterialHelper.BindClipPlane = function (effect, scene) {
  41751. if (scene.clipPlane) {
  41752. var clipPlane = scene.clipPlane;
  41753. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41754. }
  41755. };
  41756. return MaterialHelper;
  41757. }());
  41758. BABYLON.MaterialHelper = MaterialHelper;
  41759. })(BABYLON || (BABYLON = {}));
  41760. //# sourceMappingURL=babylon.materialHelper.js.map
  41761. var BABYLON;
  41762. (function (BABYLON) {
  41763. var PushMaterial = /** @class */ (function (_super) {
  41764. __extends(PushMaterial, _super);
  41765. function PushMaterial(name, scene) {
  41766. var _this = _super.call(this, name, scene) || this;
  41767. _this._normalMatrix = new BABYLON.Matrix();
  41768. _this.storeEffectOnSubMeshes = true;
  41769. return _this;
  41770. }
  41771. PushMaterial.prototype.getEffect = function () {
  41772. return this._activeEffect;
  41773. };
  41774. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41775. if (!mesh) {
  41776. return false;
  41777. }
  41778. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41779. return true;
  41780. }
  41781. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41782. };
  41783. /**
  41784. * Binds the given world matrix to the active effect
  41785. *
  41786. * @param world the matrix to bind
  41787. */
  41788. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41789. this._activeEffect.setMatrix("world", world);
  41790. };
  41791. /**
  41792. * Binds the given normal matrix to the active effect
  41793. *
  41794. * @param normalMatrix the matrix to bind
  41795. */
  41796. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41797. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41798. };
  41799. PushMaterial.prototype.bind = function (world, mesh) {
  41800. if (!mesh) {
  41801. return;
  41802. }
  41803. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41804. };
  41805. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41806. if (effect === void 0) { effect = null; }
  41807. _super.prototype._afterBind.call(this, mesh);
  41808. this.getScene()._cachedEffect = effect;
  41809. };
  41810. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41811. if (visibility === void 0) { visibility = 1; }
  41812. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41813. };
  41814. return PushMaterial;
  41815. }(BABYLON.Material));
  41816. BABYLON.PushMaterial = PushMaterial;
  41817. })(BABYLON || (BABYLON = {}));
  41818. //# sourceMappingURL=babylon.pushMaterial.js.map
  41819. var BABYLON;
  41820. (function (BABYLON) {
  41821. /** @hidden */
  41822. var StandardMaterialDefines = /** @class */ (function (_super) {
  41823. __extends(StandardMaterialDefines, _super);
  41824. function StandardMaterialDefines() {
  41825. var _this = _super.call(this) || this;
  41826. _this.MAINUV1 = false;
  41827. _this.MAINUV2 = false;
  41828. _this.DIFFUSE = false;
  41829. _this.DIFFUSEDIRECTUV = 0;
  41830. _this.AMBIENT = false;
  41831. _this.AMBIENTDIRECTUV = 0;
  41832. _this.OPACITY = false;
  41833. _this.OPACITYDIRECTUV = 0;
  41834. _this.OPACITYRGB = false;
  41835. _this.REFLECTION = false;
  41836. _this.EMISSIVE = false;
  41837. _this.EMISSIVEDIRECTUV = 0;
  41838. _this.SPECULAR = false;
  41839. _this.SPECULARDIRECTUV = 0;
  41840. _this.BUMP = false;
  41841. _this.BUMPDIRECTUV = 0;
  41842. _this.PARALLAX = false;
  41843. _this.PARALLAXOCCLUSION = false;
  41844. _this.SPECULAROVERALPHA = false;
  41845. _this.CLIPPLANE = false;
  41846. _this.ALPHATEST = false;
  41847. _this.DEPTHPREPASS = false;
  41848. _this.ALPHAFROMDIFFUSE = false;
  41849. _this.POINTSIZE = false;
  41850. _this.FOG = false;
  41851. _this.SPECULARTERM = false;
  41852. _this.DIFFUSEFRESNEL = false;
  41853. _this.OPACITYFRESNEL = false;
  41854. _this.REFLECTIONFRESNEL = false;
  41855. _this.REFRACTIONFRESNEL = false;
  41856. _this.EMISSIVEFRESNEL = false;
  41857. _this.FRESNEL = false;
  41858. _this.NORMAL = false;
  41859. _this.UV1 = false;
  41860. _this.UV2 = false;
  41861. _this.VERTEXCOLOR = false;
  41862. _this.VERTEXALPHA = false;
  41863. _this.NUM_BONE_INFLUENCERS = 0;
  41864. _this.BonesPerMesh = 0;
  41865. _this.INSTANCES = false;
  41866. _this.GLOSSINESS = false;
  41867. _this.ROUGHNESS = false;
  41868. _this.EMISSIVEASILLUMINATION = false;
  41869. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41870. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41871. _this.LIGHTMAP = false;
  41872. _this.LIGHTMAPDIRECTUV = 0;
  41873. _this.OBJECTSPACE_NORMALMAP = false;
  41874. _this.USELIGHTMAPASSHADOWMAP = false;
  41875. _this.REFLECTIONMAP_3D = false;
  41876. _this.REFLECTIONMAP_SPHERICAL = false;
  41877. _this.REFLECTIONMAP_PLANAR = false;
  41878. _this.REFLECTIONMAP_CUBIC = false;
  41879. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41880. _this.REFLECTIONMAP_PROJECTION = false;
  41881. _this.REFLECTIONMAP_SKYBOX = false;
  41882. _this.REFLECTIONMAP_EXPLICIT = false;
  41883. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41884. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41885. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41886. _this.INVERTCUBICMAP = false;
  41887. _this.LOGARITHMICDEPTH = false;
  41888. _this.REFRACTION = false;
  41889. _this.REFRACTIONMAP_3D = false;
  41890. _this.REFLECTIONOVERALPHA = false;
  41891. _this.TWOSIDEDLIGHTING = false;
  41892. _this.SHADOWFLOAT = false;
  41893. _this.MORPHTARGETS = false;
  41894. _this.MORPHTARGETS_NORMAL = false;
  41895. _this.MORPHTARGETS_TANGENT = false;
  41896. _this.NUM_MORPH_INFLUENCERS = 0;
  41897. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41898. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41899. _this.IMAGEPROCESSING = false;
  41900. _this.VIGNETTE = false;
  41901. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41902. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41903. _this.TONEMAPPING = false;
  41904. _this.CONTRAST = false;
  41905. _this.COLORCURVES = false;
  41906. _this.COLORGRADING = false;
  41907. _this.COLORGRADING3D = false;
  41908. _this.SAMPLER3DGREENDEPTH = false;
  41909. _this.SAMPLER3DBGRMAP = false;
  41910. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41911. /**
  41912. * If the reflection texture on this material is in linear color space
  41913. * @hidden
  41914. */
  41915. _this.IS_REFLECTION_LINEAR = false;
  41916. /**
  41917. * If the refraction texture on this material is in linear color space
  41918. * @hidden
  41919. */
  41920. _this.IS_REFRACTION_LINEAR = false;
  41921. _this.EXPOSURE = false;
  41922. _this.rebuild();
  41923. return _this;
  41924. }
  41925. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41926. var modes = [
  41927. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41928. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41929. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41930. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41931. ];
  41932. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41933. var mode = modes_1[_i];
  41934. this[mode] = (mode === modeToEnable);
  41935. }
  41936. };
  41937. return StandardMaterialDefines;
  41938. }(BABYLON.MaterialDefines));
  41939. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41940. var StandardMaterial = /** @class */ (function (_super) {
  41941. __extends(StandardMaterial, _super);
  41942. function StandardMaterial(name, scene) {
  41943. var _this = _super.call(this, name, scene) || this;
  41944. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41945. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41946. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41947. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41948. _this.specularPower = 64;
  41949. _this._useAlphaFromDiffuseTexture = false;
  41950. _this._useEmissiveAsIllumination = false;
  41951. _this._linkEmissiveWithDiffuse = false;
  41952. _this._useSpecularOverAlpha = false;
  41953. _this._useReflectionOverAlpha = false;
  41954. _this._disableLighting = false;
  41955. _this._useObjectSpaceNormalMap = false;
  41956. _this._useParallax = false;
  41957. _this._useParallaxOcclusion = false;
  41958. _this.parallaxScaleBias = 0.05;
  41959. _this._roughness = 0;
  41960. _this.indexOfRefraction = 0.98;
  41961. _this.invertRefractionY = true;
  41962. /**
  41963. * Defines the alpha limits in alpha test mode
  41964. */
  41965. _this.alphaCutOff = 0.4;
  41966. _this._useLightmapAsShadowmap = false;
  41967. _this._useReflectionFresnelFromSpecular = false;
  41968. _this._useGlossinessFromSpecularMapAlpha = false;
  41969. _this._maxSimultaneousLights = 4;
  41970. /**
  41971. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41972. */
  41973. _this._invertNormalMapX = false;
  41974. /**
  41975. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41976. */
  41977. _this._invertNormalMapY = false;
  41978. /**
  41979. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41980. */
  41981. _this._twoSidedLighting = false;
  41982. _this._renderTargets = new BABYLON.SmartArray(16);
  41983. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41984. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41985. // Setup the default processing configuration to the scene.
  41986. _this._attachImageProcessingConfiguration(null);
  41987. _this.getRenderTargetTextures = function () {
  41988. _this._renderTargets.reset();
  41989. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41990. _this._renderTargets.push(_this._reflectionTexture);
  41991. }
  41992. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41993. _this._renderTargets.push(_this._refractionTexture);
  41994. }
  41995. return _this._renderTargets;
  41996. };
  41997. return _this;
  41998. }
  41999. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42000. /**
  42001. * Gets the image processing configuration used either in this material.
  42002. */
  42003. get: function () {
  42004. return this._imageProcessingConfiguration;
  42005. },
  42006. /**
  42007. * Sets the Default image processing configuration used either in the this material.
  42008. *
  42009. * If sets to null, the scene one is in use.
  42010. */
  42011. set: function (value) {
  42012. this._attachImageProcessingConfiguration(value);
  42013. // Ensure the effect will be rebuilt.
  42014. this._markAllSubMeshesAsTexturesDirty();
  42015. },
  42016. enumerable: true,
  42017. configurable: true
  42018. });
  42019. /**
  42020. * Attaches a new image processing configuration to the Standard Material.
  42021. * @param configuration
  42022. */
  42023. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42024. var _this = this;
  42025. if (configuration === this._imageProcessingConfiguration) {
  42026. return;
  42027. }
  42028. // Detaches observer.
  42029. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42030. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42031. }
  42032. // Pick the scene configuration if needed.
  42033. if (!configuration) {
  42034. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42035. }
  42036. else {
  42037. this._imageProcessingConfiguration = configuration;
  42038. }
  42039. // Attaches observer.
  42040. if (this._imageProcessingConfiguration) {
  42041. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42042. _this._markAllSubMeshesAsImageProcessingDirty();
  42043. });
  42044. }
  42045. };
  42046. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42047. /**
  42048. * Gets wether the color curves effect is enabled.
  42049. */
  42050. get: function () {
  42051. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42052. },
  42053. /**
  42054. * Sets wether the color curves effect is enabled.
  42055. */
  42056. set: function (value) {
  42057. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42063. /**
  42064. * Gets wether the color grading effect is enabled.
  42065. */
  42066. get: function () {
  42067. return this.imageProcessingConfiguration.colorGradingEnabled;
  42068. },
  42069. /**
  42070. * Gets wether the color grading effect is enabled.
  42071. */
  42072. set: function (value) {
  42073. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42074. },
  42075. enumerable: true,
  42076. configurable: true
  42077. });
  42078. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42079. /**
  42080. * Gets wether tonemapping is enabled or not.
  42081. */
  42082. get: function () {
  42083. return this._imageProcessingConfiguration.toneMappingEnabled;
  42084. },
  42085. /**
  42086. * Sets wether tonemapping is enabled or not
  42087. */
  42088. set: function (value) {
  42089. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. ;
  42095. ;
  42096. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42097. /**
  42098. * The camera exposure used on this material.
  42099. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42100. * This corresponds to a photographic exposure.
  42101. */
  42102. get: function () {
  42103. return this._imageProcessingConfiguration.exposure;
  42104. },
  42105. /**
  42106. * The camera exposure used on this material.
  42107. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42108. * This corresponds to a photographic exposure.
  42109. */
  42110. set: function (value) {
  42111. this._imageProcessingConfiguration.exposure = value;
  42112. },
  42113. enumerable: true,
  42114. configurable: true
  42115. });
  42116. ;
  42117. ;
  42118. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42119. /**
  42120. * Gets The camera contrast used on this material.
  42121. */
  42122. get: function () {
  42123. return this._imageProcessingConfiguration.contrast;
  42124. },
  42125. /**
  42126. * Sets The camera contrast used on this material.
  42127. */
  42128. set: function (value) {
  42129. this._imageProcessingConfiguration.contrast = value;
  42130. },
  42131. enumerable: true,
  42132. configurable: true
  42133. });
  42134. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42135. /**
  42136. * Gets the Color Grading 2D Lookup Texture.
  42137. */
  42138. get: function () {
  42139. return this._imageProcessingConfiguration.colorGradingTexture;
  42140. },
  42141. /**
  42142. * Sets the Color Grading 2D Lookup Texture.
  42143. */
  42144. set: function (value) {
  42145. this._imageProcessingConfiguration.colorGradingTexture = value;
  42146. },
  42147. enumerable: true,
  42148. configurable: true
  42149. });
  42150. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42151. /**
  42152. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42153. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42154. * 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;
  42155. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42156. */
  42157. get: function () {
  42158. return this._imageProcessingConfiguration.colorCurves;
  42159. },
  42160. /**
  42161. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42162. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42163. * 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;
  42164. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42165. */
  42166. set: function (value) {
  42167. this._imageProcessingConfiguration.colorCurves = value;
  42168. },
  42169. enumerable: true,
  42170. configurable: true
  42171. });
  42172. StandardMaterial.prototype.getClassName = function () {
  42173. return "StandardMaterial";
  42174. };
  42175. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42176. get: function () {
  42177. return this._useLogarithmicDepth;
  42178. },
  42179. set: function (value) {
  42180. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42181. this._markAllSubMeshesAsMiscDirty();
  42182. },
  42183. enumerable: true,
  42184. configurable: true
  42185. });
  42186. StandardMaterial.prototype.needAlphaBlending = function () {
  42187. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42188. };
  42189. StandardMaterial.prototype.needAlphaTesting = function () {
  42190. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42191. };
  42192. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42193. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42194. };
  42195. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42196. return this._diffuseTexture;
  42197. };
  42198. /**
  42199. * Child classes can use it to update shaders
  42200. */
  42201. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42202. if (useInstances === void 0) { useInstances = false; }
  42203. if (subMesh.effect && this.isFrozen) {
  42204. if (this._wasPreviouslyReady && subMesh.effect) {
  42205. return true;
  42206. }
  42207. }
  42208. if (!subMesh._materialDefines) {
  42209. subMesh._materialDefines = new StandardMaterialDefines();
  42210. }
  42211. var scene = this.getScene();
  42212. var defines = subMesh._materialDefines;
  42213. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42214. if (defines._renderId === scene.getRenderId()) {
  42215. return true;
  42216. }
  42217. }
  42218. var engine = scene.getEngine();
  42219. // Lights
  42220. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42221. // Textures
  42222. if (defines._areTexturesDirty) {
  42223. defines._needUVs = false;
  42224. defines.MAINUV1 = false;
  42225. defines.MAINUV2 = false;
  42226. if (scene.texturesEnabled) {
  42227. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42228. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42229. return false;
  42230. }
  42231. else {
  42232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42233. }
  42234. }
  42235. else {
  42236. defines.DIFFUSE = false;
  42237. }
  42238. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42239. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42240. return false;
  42241. }
  42242. else {
  42243. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42244. }
  42245. }
  42246. else {
  42247. defines.AMBIENT = false;
  42248. }
  42249. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42250. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42251. return false;
  42252. }
  42253. else {
  42254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42255. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42256. }
  42257. }
  42258. else {
  42259. defines.OPACITY = false;
  42260. }
  42261. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42262. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42263. return false;
  42264. }
  42265. else {
  42266. defines._needNormals = true;
  42267. defines.REFLECTION = true;
  42268. defines.ROUGHNESS = (this._roughness > 0);
  42269. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42270. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42271. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42272. switch (this._reflectionTexture.coordinatesMode) {
  42273. case BABYLON.Texture.EXPLICIT_MODE:
  42274. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42275. break;
  42276. case BABYLON.Texture.PLANAR_MODE:
  42277. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42278. break;
  42279. case BABYLON.Texture.PROJECTION_MODE:
  42280. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42281. break;
  42282. case BABYLON.Texture.SKYBOX_MODE:
  42283. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42284. break;
  42285. case BABYLON.Texture.SPHERICAL_MODE:
  42286. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42287. break;
  42288. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42289. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42290. break;
  42291. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42292. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42293. break;
  42294. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42295. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42296. break;
  42297. case BABYLON.Texture.CUBIC_MODE:
  42298. case BABYLON.Texture.INVCUBIC_MODE:
  42299. default:
  42300. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42301. break;
  42302. }
  42303. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42304. }
  42305. }
  42306. else {
  42307. defines.REFLECTION = false;
  42308. }
  42309. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42310. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42311. return false;
  42312. }
  42313. else {
  42314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42315. }
  42316. }
  42317. else {
  42318. defines.EMISSIVE = false;
  42319. }
  42320. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42321. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42322. return false;
  42323. }
  42324. else {
  42325. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42326. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42327. }
  42328. }
  42329. else {
  42330. defines.LIGHTMAP = false;
  42331. }
  42332. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42333. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42334. return false;
  42335. }
  42336. else {
  42337. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42338. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42339. }
  42340. }
  42341. else {
  42342. defines.SPECULAR = false;
  42343. }
  42344. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42345. // Bump texure can not be not blocking.
  42346. if (!this._bumpTexture.isReady()) {
  42347. return false;
  42348. }
  42349. else {
  42350. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42351. defines.PARALLAX = this._useParallax;
  42352. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42353. }
  42354. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42355. }
  42356. else {
  42357. defines.BUMP = false;
  42358. }
  42359. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42360. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42361. return false;
  42362. }
  42363. else {
  42364. defines._needUVs = true;
  42365. defines.REFRACTION = true;
  42366. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42367. }
  42368. }
  42369. else {
  42370. defines.REFRACTION = false;
  42371. }
  42372. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42373. }
  42374. else {
  42375. defines.DIFFUSE = false;
  42376. defines.AMBIENT = false;
  42377. defines.OPACITY = false;
  42378. defines.REFLECTION = false;
  42379. defines.EMISSIVE = false;
  42380. defines.LIGHTMAP = false;
  42381. defines.BUMP = false;
  42382. defines.REFRACTION = false;
  42383. }
  42384. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42385. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42386. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42387. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42388. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42389. }
  42390. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42391. if (!this._imageProcessingConfiguration.isReady()) {
  42392. return false;
  42393. }
  42394. this._imageProcessingConfiguration.prepareDefines(defines);
  42395. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42396. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42397. }
  42398. if (defines._areFresnelDirty) {
  42399. if (StandardMaterial.FresnelEnabled) {
  42400. // Fresnel
  42401. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42402. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42403. this._reflectionFresnelParameters) {
  42404. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42405. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42406. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42407. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42408. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42409. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42410. defines._needNormals = true;
  42411. defines.FRESNEL = true;
  42412. }
  42413. }
  42414. else {
  42415. defines.FRESNEL = false;
  42416. }
  42417. }
  42418. // Misc.
  42419. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42420. // Attribs
  42421. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42422. // Values that need to be evaluated on every frame
  42423. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42424. // Get correct effect
  42425. if (defines.isDirty) {
  42426. defines.markAsProcessed();
  42427. scene.resetCachedMaterial();
  42428. // Fallbacks
  42429. var fallbacks = new BABYLON.EffectFallbacks();
  42430. if (defines.REFLECTION) {
  42431. fallbacks.addFallback(0, "REFLECTION");
  42432. }
  42433. if (defines.SPECULAR) {
  42434. fallbacks.addFallback(0, "SPECULAR");
  42435. }
  42436. if (defines.BUMP) {
  42437. fallbacks.addFallback(0, "BUMP");
  42438. }
  42439. if (defines.PARALLAX) {
  42440. fallbacks.addFallback(1, "PARALLAX");
  42441. }
  42442. if (defines.PARALLAXOCCLUSION) {
  42443. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42444. }
  42445. if (defines.SPECULAROVERALPHA) {
  42446. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42447. }
  42448. if (defines.FOG) {
  42449. fallbacks.addFallback(1, "FOG");
  42450. }
  42451. if (defines.POINTSIZE) {
  42452. fallbacks.addFallback(0, "POINTSIZE");
  42453. }
  42454. if (defines.LOGARITHMICDEPTH) {
  42455. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42456. }
  42457. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42458. if (defines.SPECULARTERM) {
  42459. fallbacks.addFallback(0, "SPECULARTERM");
  42460. }
  42461. if (defines.DIFFUSEFRESNEL) {
  42462. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42463. }
  42464. if (defines.OPACITYFRESNEL) {
  42465. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42466. }
  42467. if (defines.REFLECTIONFRESNEL) {
  42468. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42469. }
  42470. if (defines.EMISSIVEFRESNEL) {
  42471. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42472. }
  42473. if (defines.FRESNEL) {
  42474. fallbacks.addFallback(4, "FRESNEL");
  42475. }
  42476. //Attributes
  42477. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42478. if (defines.NORMAL) {
  42479. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42480. }
  42481. if (defines.UV1) {
  42482. attribs.push(BABYLON.VertexBuffer.UVKind);
  42483. }
  42484. if (defines.UV2) {
  42485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42486. }
  42487. if (defines.VERTEXCOLOR) {
  42488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42489. }
  42490. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42491. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42492. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42493. var shaderName = "default";
  42494. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42495. "vFogInfos", "vFogColor", "pointSize",
  42496. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42497. "mBones",
  42498. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42499. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42500. "vReflectionPosition", "vReflectionSize",
  42501. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42502. ];
  42503. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42504. var uniformBuffers = ["Material", "Scene"];
  42505. if (BABYLON.ImageProcessingConfiguration) {
  42506. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42507. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42508. }
  42509. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42510. uniformsNames: uniforms,
  42511. uniformBuffersNames: uniformBuffers,
  42512. samplers: samplers,
  42513. defines: defines,
  42514. maxSimultaneousLights: this._maxSimultaneousLights
  42515. });
  42516. if (this.customShaderNameResolve) {
  42517. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42518. }
  42519. var join = defines.toString();
  42520. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42521. attributes: attribs,
  42522. uniformsNames: uniforms,
  42523. uniformBuffersNames: uniformBuffers,
  42524. samplers: samplers,
  42525. defines: join,
  42526. fallbacks: fallbacks,
  42527. onCompiled: this.onCompiled,
  42528. onError: this.onError,
  42529. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42530. }, engine), defines);
  42531. this.buildUniformLayout();
  42532. }
  42533. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42534. return false;
  42535. }
  42536. defines._renderId = scene.getRenderId();
  42537. this._wasPreviouslyReady = true;
  42538. return true;
  42539. };
  42540. StandardMaterial.prototype.buildUniformLayout = function () {
  42541. // Order is important !
  42542. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42543. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42544. this._uniformBuffer.addUniform("opacityParts", 4);
  42545. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42546. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42547. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42548. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42549. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42550. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42551. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42552. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42553. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42554. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42555. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42556. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42557. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42558. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42559. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42560. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42561. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42562. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42563. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42564. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42565. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42566. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42567. this._uniformBuffer.addUniform("specularMatrix", 16);
  42568. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42569. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42570. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42571. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42572. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42573. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42574. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42575. this._uniformBuffer.addUniform("pointSize", 1);
  42576. this._uniformBuffer.create();
  42577. };
  42578. StandardMaterial.prototype.unbind = function () {
  42579. if (this._activeEffect) {
  42580. var needFlag = false;
  42581. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42582. this._activeEffect.setTexture("reflection2DSampler", null);
  42583. needFlag = true;
  42584. }
  42585. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42586. this._activeEffect.setTexture("refraction2DSampler", null);
  42587. needFlag = true;
  42588. }
  42589. if (needFlag) {
  42590. this._markAllSubMeshesAsTexturesDirty();
  42591. }
  42592. }
  42593. _super.prototype.unbind.call(this);
  42594. };
  42595. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42596. var scene = this.getScene();
  42597. var defines = subMesh._materialDefines;
  42598. if (!defines) {
  42599. return;
  42600. }
  42601. var effect = subMesh.effect;
  42602. if (!effect) {
  42603. return;
  42604. }
  42605. this._activeEffect = effect;
  42606. // Matrices
  42607. this.bindOnlyWorldMatrix(world);
  42608. // Normal Matrix
  42609. if (defines.OBJECTSPACE_NORMALMAP) {
  42610. world.toNormalMatrix(this._normalMatrix);
  42611. this.bindOnlyNormalMatrix(this._normalMatrix);
  42612. }
  42613. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42614. // Bones
  42615. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42616. if (mustRebind) {
  42617. this._uniformBuffer.bindToEffect(effect, "Material");
  42618. this.bindViewProjection(effect);
  42619. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42620. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42621. // Fresnel
  42622. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42623. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42624. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42625. }
  42626. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42627. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42628. }
  42629. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42630. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42631. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42632. }
  42633. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42634. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42635. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42636. }
  42637. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42638. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42639. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42640. }
  42641. }
  42642. // Textures
  42643. if (scene.texturesEnabled) {
  42644. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42645. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42646. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42647. if (this._diffuseTexture.hasAlpha) {
  42648. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42649. }
  42650. }
  42651. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42652. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42653. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42654. }
  42655. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42656. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42657. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42658. }
  42659. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42660. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42661. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42662. if (this._reflectionTexture.boundingBoxSize) {
  42663. var cubeTexture = this._reflectionTexture;
  42664. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42665. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42666. }
  42667. }
  42668. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42669. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42670. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42671. }
  42672. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42673. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42674. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42675. }
  42676. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42677. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42678. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42679. }
  42680. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42681. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42682. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42683. if (scene._mirroredCameraPosition) {
  42684. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42685. }
  42686. else {
  42687. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42688. }
  42689. }
  42690. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42691. var depth = 1.0;
  42692. if (!this._refractionTexture.isCube) {
  42693. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42694. if (this._refractionTexture.depth) {
  42695. depth = this._refractionTexture.depth;
  42696. }
  42697. }
  42698. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42699. }
  42700. }
  42701. // Point size
  42702. if (this.pointsCloud) {
  42703. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42704. }
  42705. if (defines.SPECULARTERM) {
  42706. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42707. }
  42708. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42709. // Diffuse
  42710. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42711. }
  42712. // Textures
  42713. if (scene.texturesEnabled) {
  42714. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42715. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42716. }
  42717. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42718. effect.setTexture("ambientSampler", this._ambientTexture);
  42719. }
  42720. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42721. effect.setTexture("opacitySampler", this._opacityTexture);
  42722. }
  42723. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42724. if (this._reflectionTexture.isCube) {
  42725. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42726. }
  42727. else {
  42728. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42729. }
  42730. }
  42731. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42732. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42733. }
  42734. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42735. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42736. }
  42737. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42738. effect.setTexture("specularSampler", this._specularTexture);
  42739. }
  42740. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42741. effect.setTexture("bumpSampler", this._bumpTexture);
  42742. }
  42743. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42744. var depth = 1.0;
  42745. if (this._refractionTexture.isCube) {
  42746. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42747. }
  42748. else {
  42749. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42750. }
  42751. }
  42752. }
  42753. // Clip plane
  42754. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42755. // Colors
  42756. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42757. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42758. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42759. }
  42760. if (mustRebind || !this.isFrozen) {
  42761. // Lights
  42762. if (scene.lightsEnabled && !this._disableLighting) {
  42763. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42764. }
  42765. // View
  42766. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42767. this.bindView(effect);
  42768. }
  42769. // Fog
  42770. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42771. // Morph targets
  42772. if (defines.NUM_MORPH_INFLUENCERS) {
  42773. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42774. }
  42775. // Log. depth
  42776. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42777. // image processing
  42778. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42779. this._imageProcessingConfiguration.bind(this._activeEffect);
  42780. }
  42781. }
  42782. this._uniformBuffer.update();
  42783. this._afterBind(mesh, this._activeEffect);
  42784. };
  42785. StandardMaterial.prototype.getAnimatables = function () {
  42786. var results = [];
  42787. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42788. results.push(this._diffuseTexture);
  42789. }
  42790. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42791. results.push(this._ambientTexture);
  42792. }
  42793. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42794. results.push(this._opacityTexture);
  42795. }
  42796. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42797. results.push(this._reflectionTexture);
  42798. }
  42799. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42800. results.push(this._emissiveTexture);
  42801. }
  42802. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42803. results.push(this._specularTexture);
  42804. }
  42805. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42806. results.push(this._bumpTexture);
  42807. }
  42808. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42809. results.push(this._lightmapTexture);
  42810. }
  42811. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42812. results.push(this._refractionTexture);
  42813. }
  42814. return results;
  42815. };
  42816. StandardMaterial.prototype.getActiveTextures = function () {
  42817. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42818. if (this._diffuseTexture) {
  42819. activeTextures.push(this._diffuseTexture);
  42820. }
  42821. if (this._ambientTexture) {
  42822. activeTextures.push(this._ambientTexture);
  42823. }
  42824. if (this._opacityTexture) {
  42825. activeTextures.push(this._opacityTexture);
  42826. }
  42827. if (this._reflectionTexture) {
  42828. activeTextures.push(this._reflectionTexture);
  42829. }
  42830. if (this._emissiveTexture) {
  42831. activeTextures.push(this._emissiveTexture);
  42832. }
  42833. if (this._specularTexture) {
  42834. activeTextures.push(this._specularTexture);
  42835. }
  42836. if (this._bumpTexture) {
  42837. activeTextures.push(this._bumpTexture);
  42838. }
  42839. if (this._lightmapTexture) {
  42840. activeTextures.push(this._lightmapTexture);
  42841. }
  42842. if (this._refractionTexture) {
  42843. activeTextures.push(this._refractionTexture);
  42844. }
  42845. return activeTextures;
  42846. };
  42847. StandardMaterial.prototype.hasTexture = function (texture) {
  42848. if (_super.prototype.hasTexture.call(this, texture)) {
  42849. return true;
  42850. }
  42851. if (this._diffuseTexture === texture) {
  42852. return true;
  42853. }
  42854. if (this._ambientTexture === texture) {
  42855. return true;
  42856. }
  42857. if (this._opacityTexture === texture) {
  42858. return true;
  42859. }
  42860. if (this._reflectionTexture === texture) {
  42861. return true;
  42862. }
  42863. if (this._emissiveTexture === texture) {
  42864. return true;
  42865. }
  42866. if (this._specularTexture === texture) {
  42867. return true;
  42868. }
  42869. if (this._bumpTexture === texture) {
  42870. return true;
  42871. }
  42872. if (this._lightmapTexture === texture) {
  42873. return true;
  42874. }
  42875. if (this._refractionTexture === texture) {
  42876. return true;
  42877. }
  42878. return false;
  42879. };
  42880. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42881. if (forceDisposeTextures) {
  42882. if (this._diffuseTexture) {
  42883. this._diffuseTexture.dispose();
  42884. }
  42885. if (this._ambientTexture) {
  42886. this._ambientTexture.dispose();
  42887. }
  42888. if (this._opacityTexture) {
  42889. this._opacityTexture.dispose();
  42890. }
  42891. if (this._reflectionTexture) {
  42892. this._reflectionTexture.dispose();
  42893. }
  42894. if (this._emissiveTexture) {
  42895. this._emissiveTexture.dispose();
  42896. }
  42897. if (this._specularTexture) {
  42898. this._specularTexture.dispose();
  42899. }
  42900. if (this._bumpTexture) {
  42901. this._bumpTexture.dispose();
  42902. }
  42903. if (this._lightmapTexture) {
  42904. this._lightmapTexture.dispose();
  42905. }
  42906. if (this._refractionTexture) {
  42907. this._refractionTexture.dispose();
  42908. }
  42909. }
  42910. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42911. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42912. }
  42913. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42914. };
  42915. StandardMaterial.prototype.clone = function (name) {
  42916. var _this = this;
  42917. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42918. result.name = name;
  42919. result.id = name;
  42920. return result;
  42921. };
  42922. StandardMaterial.prototype.serialize = function () {
  42923. return BABYLON.SerializationHelper.Serialize(this);
  42924. };
  42925. // Statics
  42926. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42927. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42928. };
  42929. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42930. get: function () {
  42931. return StandardMaterial._DiffuseTextureEnabled;
  42932. },
  42933. set: function (value) {
  42934. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42935. return;
  42936. }
  42937. StandardMaterial._DiffuseTextureEnabled = value;
  42938. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42939. },
  42940. enumerable: true,
  42941. configurable: true
  42942. });
  42943. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42944. get: function () {
  42945. return StandardMaterial._AmbientTextureEnabled;
  42946. },
  42947. set: function (value) {
  42948. if (StandardMaterial._AmbientTextureEnabled === value) {
  42949. return;
  42950. }
  42951. StandardMaterial._AmbientTextureEnabled = value;
  42952. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42953. },
  42954. enumerable: true,
  42955. configurable: true
  42956. });
  42957. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42958. get: function () {
  42959. return StandardMaterial._OpacityTextureEnabled;
  42960. },
  42961. set: function (value) {
  42962. if (StandardMaterial._OpacityTextureEnabled === value) {
  42963. return;
  42964. }
  42965. StandardMaterial._OpacityTextureEnabled = value;
  42966. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42967. },
  42968. enumerable: true,
  42969. configurable: true
  42970. });
  42971. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42972. get: function () {
  42973. return StandardMaterial._ReflectionTextureEnabled;
  42974. },
  42975. set: function (value) {
  42976. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42977. return;
  42978. }
  42979. StandardMaterial._ReflectionTextureEnabled = value;
  42980. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42981. },
  42982. enumerable: true,
  42983. configurable: true
  42984. });
  42985. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42986. get: function () {
  42987. return StandardMaterial._EmissiveTextureEnabled;
  42988. },
  42989. set: function (value) {
  42990. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42991. return;
  42992. }
  42993. StandardMaterial._EmissiveTextureEnabled = value;
  42994. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42995. },
  42996. enumerable: true,
  42997. configurable: true
  42998. });
  42999. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43000. get: function () {
  43001. return StandardMaterial._SpecularTextureEnabled;
  43002. },
  43003. set: function (value) {
  43004. if (StandardMaterial._SpecularTextureEnabled === value) {
  43005. return;
  43006. }
  43007. StandardMaterial._SpecularTextureEnabled = value;
  43008. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43009. },
  43010. enumerable: true,
  43011. configurable: true
  43012. });
  43013. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43014. get: function () {
  43015. return StandardMaterial._BumpTextureEnabled;
  43016. },
  43017. set: function (value) {
  43018. if (StandardMaterial._BumpTextureEnabled === value) {
  43019. return;
  43020. }
  43021. StandardMaterial._BumpTextureEnabled = value;
  43022. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43023. },
  43024. enumerable: true,
  43025. configurable: true
  43026. });
  43027. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43028. get: function () {
  43029. return StandardMaterial._LightmapTextureEnabled;
  43030. },
  43031. set: function (value) {
  43032. if (StandardMaterial._LightmapTextureEnabled === value) {
  43033. return;
  43034. }
  43035. StandardMaterial._LightmapTextureEnabled = value;
  43036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43037. },
  43038. enumerable: true,
  43039. configurable: true
  43040. });
  43041. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43042. get: function () {
  43043. return StandardMaterial._RefractionTextureEnabled;
  43044. },
  43045. set: function (value) {
  43046. if (StandardMaterial._RefractionTextureEnabled === value) {
  43047. return;
  43048. }
  43049. StandardMaterial._RefractionTextureEnabled = value;
  43050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43051. },
  43052. enumerable: true,
  43053. configurable: true
  43054. });
  43055. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43056. get: function () {
  43057. return StandardMaterial._ColorGradingTextureEnabled;
  43058. },
  43059. set: function (value) {
  43060. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43061. return;
  43062. }
  43063. StandardMaterial._ColorGradingTextureEnabled = value;
  43064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43065. },
  43066. enumerable: true,
  43067. configurable: true
  43068. });
  43069. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43070. get: function () {
  43071. return StandardMaterial._FresnelEnabled;
  43072. },
  43073. set: function (value) {
  43074. if (StandardMaterial._FresnelEnabled === value) {
  43075. return;
  43076. }
  43077. StandardMaterial._FresnelEnabled = value;
  43078. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43079. },
  43080. enumerable: true,
  43081. configurable: true
  43082. });
  43083. // Flags used to enable or disable a type of texture for all Standard Materials
  43084. StandardMaterial._DiffuseTextureEnabled = true;
  43085. StandardMaterial._AmbientTextureEnabled = true;
  43086. StandardMaterial._OpacityTextureEnabled = true;
  43087. StandardMaterial._ReflectionTextureEnabled = true;
  43088. StandardMaterial._EmissiveTextureEnabled = true;
  43089. StandardMaterial._SpecularTextureEnabled = true;
  43090. StandardMaterial._BumpTextureEnabled = true;
  43091. StandardMaterial._LightmapTextureEnabled = true;
  43092. StandardMaterial._RefractionTextureEnabled = true;
  43093. StandardMaterial._ColorGradingTextureEnabled = true;
  43094. StandardMaterial._FresnelEnabled = true;
  43095. __decorate([
  43096. BABYLON.serializeAsTexture("diffuseTexture")
  43097. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43098. __decorate([
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43100. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43101. __decorate([
  43102. BABYLON.serializeAsTexture("ambientTexture")
  43103. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43104. __decorate([
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serializeAsTexture("opacityTexture")
  43109. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43110. __decorate([
  43111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43112. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43113. __decorate([
  43114. BABYLON.serializeAsTexture("reflectionTexture")
  43115. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43116. __decorate([
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsTexture("emissiveTexture")
  43121. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43122. __decorate([
  43123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43124. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43125. __decorate([
  43126. BABYLON.serializeAsTexture("specularTexture")
  43127. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43128. __decorate([
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43130. ], StandardMaterial.prototype, "specularTexture", void 0);
  43131. __decorate([
  43132. BABYLON.serializeAsTexture("bumpTexture")
  43133. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43134. __decorate([
  43135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43136. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43137. __decorate([
  43138. BABYLON.serializeAsTexture("lightmapTexture")
  43139. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43140. __decorate([
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43143. __decorate([
  43144. BABYLON.serializeAsTexture("refractionTexture")
  43145. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43146. __decorate([
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43149. __decorate([
  43150. BABYLON.serializeAsColor3("ambient")
  43151. ], StandardMaterial.prototype, "ambientColor", void 0);
  43152. __decorate([
  43153. BABYLON.serializeAsColor3("diffuse")
  43154. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43155. __decorate([
  43156. BABYLON.serializeAsColor3("specular")
  43157. ], StandardMaterial.prototype, "specularColor", void 0);
  43158. __decorate([
  43159. BABYLON.serializeAsColor3("emissive")
  43160. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43161. __decorate([
  43162. BABYLON.serialize()
  43163. ], StandardMaterial.prototype, "specularPower", void 0);
  43164. __decorate([
  43165. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43166. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43170. __decorate([
  43171. BABYLON.serialize("useEmissiveAsIllumination")
  43172. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43176. __decorate([
  43177. BABYLON.serialize("linkEmissiveWithDiffuse")
  43178. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43182. __decorate([
  43183. BABYLON.serialize("useSpecularOverAlpha")
  43184. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43185. __decorate([
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43187. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43188. __decorate([
  43189. BABYLON.serialize("useReflectionOverAlpha")
  43190. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43194. __decorate([
  43195. BABYLON.serialize("disableLighting")
  43196. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43197. __decorate([
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43199. ], StandardMaterial.prototype, "disableLighting", void 0);
  43200. __decorate([
  43201. BABYLON.serialize("useObjectSpaceNormalMap")
  43202. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43203. __decorate([
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43206. __decorate([
  43207. BABYLON.serialize("useParallax")
  43208. ], StandardMaterial.prototype, "_useParallax", void 0);
  43209. __decorate([
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43211. ], StandardMaterial.prototype, "useParallax", void 0);
  43212. __decorate([
  43213. BABYLON.serialize("useParallaxOcclusion")
  43214. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43218. __decorate([
  43219. BABYLON.serialize()
  43220. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43221. __decorate([
  43222. BABYLON.serialize("roughness")
  43223. ], StandardMaterial.prototype, "_roughness", void 0);
  43224. __decorate([
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43226. ], StandardMaterial.prototype, "roughness", void 0);
  43227. __decorate([
  43228. BABYLON.serialize()
  43229. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43230. __decorate([
  43231. BABYLON.serialize()
  43232. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43233. __decorate([
  43234. BABYLON.serialize()
  43235. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43236. __decorate([
  43237. BABYLON.serialize("useLightmapAsShadowmap")
  43238. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43239. __decorate([
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43241. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43242. __decorate([
  43243. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43244. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43245. __decorate([
  43246. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43247. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43248. __decorate([
  43249. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43250. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43251. __decorate([
  43252. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43253. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43254. __decorate([
  43255. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43256. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43257. __decorate([
  43258. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43259. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43260. __decorate([
  43261. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43262. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43263. __decorate([
  43264. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43265. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43266. __decorate([
  43267. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43268. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43269. __decorate([
  43270. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43271. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43272. __decorate([
  43273. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43274. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43275. __decorate([
  43276. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43277. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43278. __decorate([
  43279. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43280. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43281. __decorate([
  43282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43283. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43284. __decorate([
  43285. BABYLON.serialize("maxSimultaneousLights")
  43286. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43287. __decorate([
  43288. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43289. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43290. __decorate([
  43291. BABYLON.serialize("invertNormalMapX")
  43292. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43293. __decorate([
  43294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43295. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43296. __decorate([
  43297. BABYLON.serialize("invertNormalMapY")
  43298. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43299. __decorate([
  43300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43301. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43302. __decorate([
  43303. BABYLON.serialize("twoSidedLighting")
  43304. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43305. __decorate([
  43306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43307. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43308. __decorate([
  43309. BABYLON.serialize()
  43310. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43311. return StandardMaterial;
  43312. }(BABYLON.PushMaterial));
  43313. BABYLON.StandardMaterial = StandardMaterial;
  43314. })(BABYLON || (BABYLON = {}));
  43315. //# sourceMappingURL=babylon.standardMaterial.js.map
  43316. var BABYLON;
  43317. (function (BABYLON) {
  43318. /**
  43319. * Manages the defines for the PBR Material.
  43320. * @hiddenChildren
  43321. */
  43322. var PBRMaterialDefines = /** @class */ (function (_super) {
  43323. __extends(PBRMaterialDefines, _super);
  43324. /**
  43325. * Initializes the PBR Material defines.
  43326. */
  43327. function PBRMaterialDefines() {
  43328. var _this = _super.call(this) || this;
  43329. _this.PBR = true;
  43330. _this.MAINUV1 = false;
  43331. _this.MAINUV2 = false;
  43332. _this.UV1 = false;
  43333. _this.UV2 = false;
  43334. _this.ALBEDO = false;
  43335. _this.ALBEDODIRECTUV = 0;
  43336. _this.VERTEXCOLOR = false;
  43337. _this.AMBIENT = false;
  43338. _this.AMBIENTDIRECTUV = 0;
  43339. _this.AMBIENTINGRAYSCALE = false;
  43340. _this.OPACITY = false;
  43341. _this.VERTEXALPHA = false;
  43342. _this.OPACITYDIRECTUV = 0;
  43343. _this.OPACITYRGB = false;
  43344. _this.ALPHATEST = false;
  43345. _this.DEPTHPREPASS = false;
  43346. _this.ALPHABLEND = false;
  43347. _this.ALPHAFROMALBEDO = false;
  43348. _this.ALPHATESTVALUE = "0.5";
  43349. _this.SPECULAROVERALPHA = false;
  43350. _this.RADIANCEOVERALPHA = false;
  43351. _this.ALPHAFRESNEL = false;
  43352. _this.LINEARALPHAFRESNEL = false;
  43353. _this.PREMULTIPLYALPHA = false;
  43354. _this.EMISSIVE = false;
  43355. _this.EMISSIVEDIRECTUV = 0;
  43356. _this.REFLECTIVITY = false;
  43357. _this.REFLECTIVITYDIRECTUV = 0;
  43358. _this.SPECULARTERM = false;
  43359. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43360. _this.MICROSURFACEAUTOMATIC = false;
  43361. _this.LODBASEDMICROSFURACE = false;
  43362. _this.MICROSURFACEMAP = false;
  43363. _this.MICROSURFACEMAPDIRECTUV = 0;
  43364. _this.METALLICWORKFLOW = false;
  43365. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43366. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43367. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43368. _this.AOSTOREINMETALMAPRED = false;
  43369. _this.ENVIRONMENTBRDF = false;
  43370. _this.NORMAL = false;
  43371. _this.TANGENT = false;
  43372. _this.BUMP = false;
  43373. _this.BUMPDIRECTUV = 0;
  43374. _this.OBJECTSPACE_NORMALMAP = false;
  43375. _this.PARALLAX = false;
  43376. _this.PARALLAXOCCLUSION = false;
  43377. _this.NORMALXYSCALE = true;
  43378. _this.LIGHTMAP = false;
  43379. _this.LIGHTMAPDIRECTUV = 0;
  43380. _this.USELIGHTMAPASSHADOWMAP = false;
  43381. _this.GAMMALIGHTMAP = false;
  43382. _this.REFLECTION = false;
  43383. _this.REFLECTIONMAP_3D = false;
  43384. _this.REFLECTIONMAP_SPHERICAL = false;
  43385. _this.REFLECTIONMAP_PLANAR = false;
  43386. _this.REFLECTIONMAP_CUBIC = false;
  43387. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43388. _this.REFLECTIONMAP_PROJECTION = false;
  43389. _this.REFLECTIONMAP_SKYBOX = false;
  43390. _this.REFLECTIONMAP_EXPLICIT = false;
  43391. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43392. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43393. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43394. _this.INVERTCUBICMAP = false;
  43395. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43396. _this.USESPHERICALINVERTEX = false;
  43397. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43398. _this.LODINREFLECTIONALPHA = false;
  43399. _this.GAMMAREFLECTION = false;
  43400. _this.RGBDREFLECTION = false;
  43401. _this.RADIANCEOCCLUSION = false;
  43402. _this.HORIZONOCCLUSION = false;
  43403. _this.REFRACTION = false;
  43404. _this.REFRACTIONMAP_3D = false;
  43405. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43406. _this.LODINREFRACTIONALPHA = false;
  43407. _this.GAMMAREFRACTION = false;
  43408. _this.RGBDREFRACTION = false;
  43409. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43410. _this.INSTANCES = false;
  43411. _this.NUM_BONE_INFLUENCERS = 0;
  43412. _this.BonesPerMesh = 0;
  43413. _this.NONUNIFORMSCALING = false;
  43414. _this.MORPHTARGETS = false;
  43415. _this.MORPHTARGETS_NORMAL = false;
  43416. _this.MORPHTARGETS_TANGENT = false;
  43417. _this.NUM_MORPH_INFLUENCERS = 0;
  43418. _this.IMAGEPROCESSING = false;
  43419. _this.VIGNETTE = false;
  43420. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43421. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43422. _this.TONEMAPPING = false;
  43423. _this.CONTRAST = false;
  43424. _this.COLORCURVES = false;
  43425. _this.COLORGRADING = false;
  43426. _this.COLORGRADING3D = false;
  43427. _this.SAMPLER3DGREENDEPTH = false;
  43428. _this.SAMPLER3DBGRMAP = false;
  43429. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43430. _this.EXPOSURE = false;
  43431. _this.USEPHYSICALLIGHTFALLOFF = false;
  43432. _this.TWOSIDEDLIGHTING = false;
  43433. _this.SHADOWFLOAT = false;
  43434. _this.CLIPPLANE = false;
  43435. _this.POINTSIZE = false;
  43436. _this.FOG = false;
  43437. _this.LOGARITHMICDEPTH = false;
  43438. _this.FORCENORMALFORWARD = false;
  43439. _this.SPECULARAA = false;
  43440. _this.UNLIT = false;
  43441. _this.rebuild();
  43442. return _this;
  43443. }
  43444. /**
  43445. * Resets the PBR Material defines.
  43446. */
  43447. PBRMaterialDefines.prototype.reset = function () {
  43448. _super.prototype.reset.call(this);
  43449. this.ALPHATESTVALUE = "0.5";
  43450. this.PBR = true;
  43451. };
  43452. return PBRMaterialDefines;
  43453. }(BABYLON.MaterialDefines));
  43454. /**
  43455. * The Physically based material base class of BJS.
  43456. *
  43457. * This offers the main features of a standard PBR material.
  43458. * For more information, please refer to the documentation :
  43459. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43460. */
  43461. var PBRBaseMaterial = /** @class */ (function (_super) {
  43462. __extends(PBRBaseMaterial, _super);
  43463. /**
  43464. * Instantiates a new PBRMaterial instance.
  43465. *
  43466. * @param name The material name
  43467. * @param scene The scene the material will be use in.
  43468. */
  43469. function PBRBaseMaterial(name, scene) {
  43470. var _this = _super.call(this, name, scene) || this;
  43471. /**
  43472. * Intensity of the direct lights e.g. the four lights available in your scene.
  43473. * This impacts both the direct diffuse and specular highlights.
  43474. */
  43475. _this._directIntensity = 1.0;
  43476. /**
  43477. * Intensity of the emissive part of the material.
  43478. * This helps controlling the emissive effect without modifying the emissive color.
  43479. */
  43480. _this._emissiveIntensity = 1.0;
  43481. /**
  43482. * Intensity of the environment e.g. how much the environment will light the object
  43483. * either through harmonics for rough material or through the refelction for shiny ones.
  43484. */
  43485. _this._environmentIntensity = 1.0;
  43486. /**
  43487. * This is a special control allowing the reduction of the specular highlights coming from the
  43488. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43489. */
  43490. _this._specularIntensity = 1.0;
  43491. /**
  43492. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43493. */
  43494. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43495. /**
  43496. * Debug Control allowing disabling the bump map on this material.
  43497. */
  43498. _this._disableBumpMap = false;
  43499. /**
  43500. * AKA Occlusion Texture Intensity in other nomenclature.
  43501. */
  43502. _this._ambientTextureStrength = 1.0;
  43503. /**
  43504. * The color of a material in ambient lighting.
  43505. */
  43506. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43507. /**
  43508. * AKA Diffuse Color in other nomenclature.
  43509. */
  43510. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43511. /**
  43512. * AKA Specular Color in other nomenclature.
  43513. */
  43514. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43515. /**
  43516. * The color applied when light is reflected from a material.
  43517. */
  43518. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43519. /**
  43520. * The color applied when light is emitted from a material.
  43521. */
  43522. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43523. /**
  43524. * AKA Glossiness in other nomenclature.
  43525. */
  43526. _this._microSurface = 0.9;
  43527. /**
  43528. * source material index of refraction (IOR)' / 'destination material IOR.
  43529. */
  43530. _this._indexOfRefraction = 0.66;
  43531. /**
  43532. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43533. */
  43534. _this._invertRefractionY = false;
  43535. /**
  43536. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43537. * Materials half opaque for instance using refraction could benefit from this control.
  43538. */
  43539. _this._linkRefractionWithTransparency = false;
  43540. /**
  43541. * Specifies that the material will use the light map as a show map.
  43542. */
  43543. _this._useLightmapAsShadowmap = false;
  43544. /**
  43545. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43546. * makes the reflect vector face the model (under horizon).
  43547. */
  43548. _this._useHorizonOcclusion = true;
  43549. /**
  43550. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43551. * too much the area relying on ambient texture to define their ambient occlusion.
  43552. */
  43553. _this._useRadianceOcclusion = true;
  43554. /**
  43555. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43556. */
  43557. _this._useAlphaFromAlbedoTexture = false;
  43558. /**
  43559. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43560. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43561. */
  43562. _this._useSpecularOverAlpha = true;
  43563. /**
  43564. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43565. */
  43566. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43567. /**
  43568. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43569. */
  43570. _this._useRoughnessFromMetallicTextureAlpha = true;
  43571. /**
  43572. * Specifies if the metallic texture contains the roughness information in its green channel.
  43573. */
  43574. _this._useRoughnessFromMetallicTextureGreen = false;
  43575. /**
  43576. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43577. */
  43578. _this._useMetallnessFromMetallicTextureBlue = false;
  43579. /**
  43580. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43581. */
  43582. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43583. /**
  43584. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43585. */
  43586. _this._useAmbientInGrayScale = false;
  43587. /**
  43588. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43589. * The material will try to infer what glossiness each pixel should be.
  43590. */
  43591. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43592. /**
  43593. * BJS is using an harcoded light falloff based on a manually sets up range.
  43594. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43595. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43596. */
  43597. _this._usePhysicalLightFalloff = true;
  43598. /**
  43599. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43600. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43601. */
  43602. _this._useRadianceOverAlpha = true;
  43603. /**
  43604. * Allows using an object space normal map (instead of tangent space).
  43605. */
  43606. _this._useObjectSpaceNormalMap = false;
  43607. /**
  43608. * Allows using the bump map in parallax mode.
  43609. */
  43610. _this._useParallax = false;
  43611. /**
  43612. * Allows using the bump map in parallax occlusion mode.
  43613. */
  43614. _this._useParallaxOcclusion = false;
  43615. /**
  43616. * Controls the scale bias of the parallax mode.
  43617. */
  43618. _this._parallaxScaleBias = 0.05;
  43619. /**
  43620. * If sets to true, disables all the lights affecting the material.
  43621. */
  43622. _this._disableLighting = false;
  43623. /**
  43624. * Number of Simultaneous lights allowed on the material.
  43625. */
  43626. _this._maxSimultaneousLights = 4;
  43627. /**
  43628. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43629. */
  43630. _this._invertNormalMapX = false;
  43631. /**
  43632. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43633. */
  43634. _this._invertNormalMapY = false;
  43635. /**
  43636. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43637. */
  43638. _this._twoSidedLighting = false;
  43639. /**
  43640. * Defines the alpha limits in alpha test mode.
  43641. */
  43642. _this._alphaCutOff = 0.4;
  43643. /**
  43644. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43645. */
  43646. _this._forceAlphaTest = false;
  43647. /**
  43648. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43649. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43650. */
  43651. _this._useAlphaFresnel = false;
  43652. /**
  43653. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43654. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43655. */
  43656. _this._useLinearAlphaFresnel = false;
  43657. /**
  43658. * The transparency mode of the material.
  43659. */
  43660. _this._transparencyMode = null;
  43661. /**
  43662. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43663. * from cos thetav and roughness:
  43664. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43665. */
  43666. _this._environmentBRDFTexture = null;
  43667. /**
  43668. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43669. */
  43670. _this._forceIrradianceInFragment = false;
  43671. /**
  43672. * Force normal to face away from face.
  43673. */
  43674. _this._forceNormalForward = false;
  43675. /**
  43676. * Enables specular anti aliasing in the PBR shader.
  43677. * It will both interacts on the Geometry for analytical and IBL lighting.
  43678. * It also prefilter the roughness map based on the bump values.
  43679. */
  43680. _this._enableSpecularAntiAliasing = false;
  43681. /**
  43682. * Stores the available render targets.
  43683. */
  43684. _this._renderTargets = new BABYLON.SmartArray(16);
  43685. /**
  43686. * Sets the global ambient color for the material used in lighting calculations.
  43687. */
  43688. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43689. /**
  43690. * If set to true, no lighting calculations will be applied.
  43691. */
  43692. _this._unlit = false;
  43693. // Setup the default processing configuration to the scene.
  43694. _this._attachImageProcessingConfiguration(null);
  43695. _this.getRenderTargetTextures = function () {
  43696. _this._renderTargets.reset();
  43697. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43698. _this._renderTargets.push(_this._reflectionTexture);
  43699. }
  43700. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43701. _this._renderTargets.push(_this._refractionTexture);
  43702. }
  43703. return _this._renderTargets;
  43704. };
  43705. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43706. return _this;
  43707. }
  43708. /**
  43709. * Attaches a new image processing configuration to the PBR Material.
  43710. * @param configuration
  43711. */
  43712. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43713. var _this = this;
  43714. if (configuration === this._imageProcessingConfiguration) {
  43715. return;
  43716. }
  43717. // Detaches observer.
  43718. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43719. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43720. }
  43721. // Pick the scene configuration if needed.
  43722. if (!configuration) {
  43723. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43724. }
  43725. else {
  43726. this._imageProcessingConfiguration = configuration;
  43727. }
  43728. // Attaches observer.
  43729. if (this._imageProcessingConfiguration) {
  43730. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43731. _this._markAllSubMeshesAsImageProcessingDirty();
  43732. });
  43733. }
  43734. };
  43735. /**
  43736. * Gets the name of the material class.
  43737. */
  43738. PBRBaseMaterial.prototype.getClassName = function () {
  43739. return "PBRBaseMaterial";
  43740. };
  43741. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43742. /**
  43743. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43744. */
  43745. get: function () {
  43746. return this._useLogarithmicDepth;
  43747. },
  43748. /**
  43749. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43750. */
  43751. set: function (value) {
  43752. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43753. },
  43754. enumerable: true,
  43755. configurable: true
  43756. });
  43757. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43758. /**
  43759. * Gets the current transparency mode.
  43760. */
  43761. get: function () {
  43762. return this._transparencyMode;
  43763. },
  43764. /**
  43765. * Sets the transparency mode of the material.
  43766. *
  43767. * | Value | Type | Description |
  43768. * | ----- | ----------------------------------- | ----------- |
  43769. * | 0 | OPAQUE | |
  43770. * | 1 | ALPHATEST | |
  43771. * | 2 | ALPHABLEND | |
  43772. * | 3 | ALPHATESTANDBLEND | |
  43773. *
  43774. */
  43775. set: function (value) {
  43776. if (this._transparencyMode === value) {
  43777. return;
  43778. }
  43779. this._transparencyMode = value;
  43780. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43781. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43782. },
  43783. enumerable: true,
  43784. configurable: true
  43785. });
  43786. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43787. /**
  43788. * Returns true if alpha blending should be disabled.
  43789. */
  43790. get: function () {
  43791. return (this._linkRefractionWithTransparency ||
  43792. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43793. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. /**
  43799. * Specifies whether or not this material should be rendered in alpha blend mode.
  43800. */
  43801. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43802. if (this._disableAlphaBlending) {
  43803. return false;
  43804. }
  43805. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43806. };
  43807. /**
  43808. * Specifies if the mesh will require alpha blending.
  43809. * @param mesh - BJS mesh.
  43810. */
  43811. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43812. if (this._disableAlphaBlending) {
  43813. return false;
  43814. }
  43815. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43816. };
  43817. /**
  43818. * Specifies whether or not this material should be rendered in alpha test mode.
  43819. */
  43820. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43821. if (this._forceAlphaTest) {
  43822. return true;
  43823. }
  43824. if (this._linkRefractionWithTransparency) {
  43825. return false;
  43826. }
  43827. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43828. };
  43829. /**
  43830. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43831. */
  43832. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43833. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43834. };
  43835. /**
  43836. * Gets the texture used for the alpha test.
  43837. */
  43838. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43839. return this._albedoTexture;
  43840. };
  43841. /**
  43842. * Specifies that the submesh is ready to be used.
  43843. * @param mesh - BJS mesh.
  43844. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43845. * @param useInstances - Specifies that instances should be used.
  43846. * @returns - boolean indicating that the submesh is ready or not.
  43847. */
  43848. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43849. if (subMesh.effect && this.isFrozen) {
  43850. if (this._wasPreviouslyReady) {
  43851. return true;
  43852. }
  43853. }
  43854. if (!subMesh._materialDefines) {
  43855. subMesh._materialDefines = new PBRMaterialDefines();
  43856. }
  43857. var defines = subMesh._materialDefines;
  43858. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43859. if (defines._renderId === this.getScene().getRenderId()) {
  43860. return true;
  43861. }
  43862. }
  43863. var scene = this.getScene();
  43864. var engine = scene.getEngine();
  43865. if (defines._areTexturesDirty) {
  43866. if (scene.texturesEnabled) {
  43867. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43868. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43869. return false;
  43870. }
  43871. }
  43872. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43873. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43874. return false;
  43875. }
  43876. }
  43877. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43878. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43879. return false;
  43880. }
  43881. }
  43882. var reflectionTexture = this._getReflectionTexture();
  43883. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43884. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43885. return false;
  43886. }
  43887. }
  43888. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43889. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43890. return false;
  43891. }
  43892. }
  43893. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43894. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43895. return false;
  43896. }
  43897. }
  43898. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43899. if (this._metallicTexture) {
  43900. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43901. return false;
  43902. }
  43903. }
  43904. else if (this._reflectivityTexture) {
  43905. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43906. return false;
  43907. }
  43908. }
  43909. if (this._microSurfaceTexture) {
  43910. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43911. return false;
  43912. }
  43913. }
  43914. }
  43915. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43916. // Bump texture cannot be not blocking.
  43917. if (!this._bumpTexture.isReady()) {
  43918. return false;
  43919. }
  43920. }
  43921. var refractionTexture = this._getRefractionTexture();
  43922. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43923. if (!refractionTexture.isReadyOrNotBlocking()) {
  43924. return false;
  43925. }
  43926. }
  43927. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43928. // This is blocking.
  43929. if (!this._environmentBRDFTexture.isReady()) {
  43930. return false;
  43931. }
  43932. }
  43933. }
  43934. }
  43935. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43936. if (!this._imageProcessingConfiguration.isReady()) {
  43937. return false;
  43938. }
  43939. }
  43940. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43941. mesh.createNormals(true);
  43942. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43943. }
  43944. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43945. if (effect) {
  43946. scene.resetCachedMaterial();
  43947. subMesh.setEffect(effect, defines);
  43948. this.buildUniformLayout();
  43949. }
  43950. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43951. return false;
  43952. }
  43953. defines._renderId = scene.getRenderId();
  43954. this._wasPreviouslyReady = true;
  43955. return true;
  43956. };
  43957. /**
  43958. * Specifies if the material uses metallic roughness workflow.
  43959. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43960. */
  43961. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43962. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43963. return true;
  43964. }
  43965. return false;
  43966. };
  43967. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43968. if (onCompiled === void 0) { onCompiled = null; }
  43969. if (onError === void 0) { onError = null; }
  43970. if (useInstances === void 0) { useInstances = null; }
  43971. if (useClipPlane === void 0) { useClipPlane = null; }
  43972. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43973. if (!defines.isDirty) {
  43974. return null;
  43975. }
  43976. defines.markAsProcessed();
  43977. var scene = this.getScene();
  43978. var engine = scene.getEngine();
  43979. // Fallbacks
  43980. var fallbacks = new BABYLON.EffectFallbacks();
  43981. var fallbackRank = 0;
  43982. if (defines.USESPHERICALINVERTEX) {
  43983. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43984. }
  43985. if (defines.FOG) {
  43986. fallbacks.addFallback(fallbackRank, "FOG");
  43987. }
  43988. if (defines.SPECULARAA) {
  43989. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43990. }
  43991. if (defines.POINTSIZE) {
  43992. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43993. }
  43994. if (defines.LOGARITHMICDEPTH) {
  43995. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43996. }
  43997. if (defines.PARALLAX) {
  43998. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43999. }
  44000. if (defines.PARALLAXOCCLUSION) {
  44001. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44002. }
  44003. if (defines.ENVIRONMENTBRDF) {
  44004. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44005. }
  44006. if (defines.TANGENT) {
  44007. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44008. }
  44009. if (defines.BUMP) {
  44010. fallbacks.addFallback(fallbackRank++, "BUMP");
  44011. }
  44012. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44013. if (defines.SPECULARTERM) {
  44014. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44015. }
  44016. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44017. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44018. }
  44019. if (defines.LIGHTMAP) {
  44020. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44021. }
  44022. if (defines.NORMAL) {
  44023. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44024. }
  44025. if (defines.AMBIENT) {
  44026. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44027. }
  44028. if (defines.EMISSIVE) {
  44029. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44030. }
  44031. if (defines.VERTEXCOLOR) {
  44032. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44033. }
  44034. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44035. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44036. }
  44037. if (defines.MORPHTARGETS) {
  44038. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44039. }
  44040. //Attributes
  44041. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44042. if (defines.NORMAL) {
  44043. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44044. }
  44045. if (defines.TANGENT) {
  44046. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44047. }
  44048. if (defines.UV1) {
  44049. attribs.push(BABYLON.VertexBuffer.UVKind);
  44050. }
  44051. if (defines.UV2) {
  44052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44053. }
  44054. if (defines.VERTEXCOLOR) {
  44055. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44056. }
  44057. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44058. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44059. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44060. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44061. "vFogInfos", "vFogColor", "pointSize",
  44062. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44063. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44064. "mBones",
  44065. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44066. "vLightingIntensity",
  44067. "logarithmicDepthConstant",
  44068. "vSphericalX", "vSphericalY", "vSphericalZ",
  44069. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44070. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44071. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44072. "vTangentSpaceParams"
  44073. ];
  44074. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44075. "bumpSampler", "lightmapSampler", "opacitySampler",
  44076. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44077. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44078. "microSurfaceSampler", "environmentBrdfSampler"];
  44079. var uniformBuffers = ["Material", "Scene"];
  44080. if (BABYLON.ImageProcessingConfiguration) {
  44081. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44082. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44083. }
  44084. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44085. uniformsNames: uniforms,
  44086. uniformBuffersNames: uniformBuffers,
  44087. samplers: samplers,
  44088. defines: defines,
  44089. maxSimultaneousLights: this._maxSimultaneousLights
  44090. });
  44091. var join = defines.toString();
  44092. return engine.createEffect("pbr", {
  44093. attributes: attribs,
  44094. uniformsNames: uniforms,
  44095. uniformBuffersNames: uniformBuffers,
  44096. samplers: samplers,
  44097. defines: join,
  44098. fallbacks: fallbacks,
  44099. onCompiled: onCompiled,
  44100. onError: onError,
  44101. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44102. }, engine);
  44103. };
  44104. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44105. if (useInstances === void 0) { useInstances = null; }
  44106. if (useClipPlane === void 0) { useClipPlane = null; }
  44107. var scene = this.getScene();
  44108. var engine = scene.getEngine();
  44109. // Lights
  44110. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44111. defines._needNormals = true;
  44112. // Textures
  44113. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44114. if (defines._areTexturesDirty) {
  44115. defines._needUVs = false;
  44116. if (scene.texturesEnabled) {
  44117. if (scene.getEngine().getCaps().textureLOD) {
  44118. defines.LODBASEDMICROSFURACE = true;
  44119. }
  44120. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44122. }
  44123. else {
  44124. defines.ALBEDO = false;
  44125. }
  44126. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44127. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44128. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44129. }
  44130. else {
  44131. defines.AMBIENT = false;
  44132. }
  44133. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44135. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44136. }
  44137. else {
  44138. defines.OPACITY = false;
  44139. }
  44140. var reflectionTexture = this._getReflectionTexture();
  44141. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44142. defines.REFLECTION = true;
  44143. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44144. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44145. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44146. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44147. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44148. defines.INVERTCUBICMAP = true;
  44149. }
  44150. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44151. switch (reflectionTexture.coordinatesMode) {
  44152. case BABYLON.Texture.EXPLICIT_MODE:
  44153. defines.REFLECTIONMAP_EXPLICIT = true;
  44154. break;
  44155. case BABYLON.Texture.PLANAR_MODE:
  44156. defines.REFLECTIONMAP_PLANAR = true;
  44157. break;
  44158. case BABYLON.Texture.PROJECTION_MODE:
  44159. defines.REFLECTIONMAP_PROJECTION = true;
  44160. break;
  44161. case BABYLON.Texture.SKYBOX_MODE:
  44162. defines.REFLECTIONMAP_SKYBOX = true;
  44163. break;
  44164. case BABYLON.Texture.SPHERICAL_MODE:
  44165. defines.REFLECTIONMAP_SPHERICAL = true;
  44166. break;
  44167. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44168. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44169. break;
  44170. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44171. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44172. break;
  44173. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44174. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44175. break;
  44176. case BABYLON.Texture.CUBIC_MODE:
  44177. case BABYLON.Texture.INVCUBIC_MODE:
  44178. default:
  44179. defines.REFLECTIONMAP_CUBIC = true;
  44180. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44181. break;
  44182. }
  44183. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44184. if (reflectionTexture.sphericalPolynomial) {
  44185. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44186. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44187. defines.USESPHERICALINVERTEX = false;
  44188. }
  44189. else {
  44190. defines.USESPHERICALINVERTEX = true;
  44191. }
  44192. }
  44193. }
  44194. }
  44195. else {
  44196. defines.REFLECTION = false;
  44197. defines.REFLECTIONMAP_3D = false;
  44198. defines.REFLECTIONMAP_SPHERICAL = false;
  44199. defines.REFLECTIONMAP_PLANAR = false;
  44200. defines.REFLECTIONMAP_CUBIC = false;
  44201. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44202. defines.REFLECTIONMAP_PROJECTION = false;
  44203. defines.REFLECTIONMAP_SKYBOX = false;
  44204. defines.REFLECTIONMAP_EXPLICIT = false;
  44205. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44207. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44208. defines.INVERTCUBICMAP = false;
  44209. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44210. defines.USESPHERICALINVERTEX = false;
  44211. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44212. defines.LODINREFLECTIONALPHA = false;
  44213. defines.GAMMAREFLECTION = false;
  44214. defines.RGBDREFLECTION = false;
  44215. }
  44216. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44218. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44219. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44220. }
  44221. else {
  44222. defines.LIGHTMAP = false;
  44223. }
  44224. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44226. }
  44227. else {
  44228. defines.EMISSIVE = false;
  44229. }
  44230. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44231. if (this._metallicTexture) {
  44232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44233. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44234. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44235. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44236. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44237. }
  44238. else if (this._reflectivityTexture) {
  44239. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44240. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44241. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44242. }
  44243. else {
  44244. defines.REFLECTIVITY = false;
  44245. }
  44246. if (this._microSurfaceTexture) {
  44247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44248. }
  44249. else {
  44250. defines.MICROSURFACEMAP = false;
  44251. }
  44252. }
  44253. else {
  44254. defines.REFLECTIVITY = false;
  44255. defines.MICROSURFACEMAP = false;
  44256. }
  44257. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44259. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44260. defines.PARALLAX = true;
  44261. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44262. }
  44263. else {
  44264. defines.PARALLAX = false;
  44265. }
  44266. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44267. }
  44268. else {
  44269. defines.BUMP = false;
  44270. }
  44271. var refractionTexture = this._getRefractionTexture();
  44272. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44273. defines.REFRACTION = true;
  44274. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44275. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44276. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44277. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44278. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44279. if (this._linkRefractionWithTransparency) {
  44280. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44281. }
  44282. }
  44283. else {
  44284. defines.REFRACTION = false;
  44285. }
  44286. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44287. defines.ENVIRONMENTBRDF = true;
  44288. }
  44289. else {
  44290. defines.ENVIRONMENTBRDF = false;
  44291. }
  44292. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44293. defines.ALPHAFROMALBEDO = true;
  44294. }
  44295. else {
  44296. defines.ALPHAFROMALBEDO = false;
  44297. }
  44298. }
  44299. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44300. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44301. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44302. if (!this.backFaceCulling && this._twoSidedLighting) {
  44303. defines.TWOSIDEDLIGHTING = true;
  44304. }
  44305. else {
  44306. defines.TWOSIDEDLIGHTING = false;
  44307. }
  44308. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44309. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44310. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44311. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44312. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44313. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44314. }
  44315. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44316. this._imageProcessingConfiguration.prepareDefines(defines);
  44317. }
  44318. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44319. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44320. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44321. // Misc.
  44322. if (defines._areMiscDirty) {
  44323. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44324. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44325. }
  44326. // Values that need to be evaluated on every frame
  44327. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44328. // Attribs
  44329. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44330. };
  44331. /**
  44332. * Force shader compilation
  44333. */
  44334. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44335. var _this = this;
  44336. var localOptions = __assign({ clipPlane: false }, options);
  44337. var defines = new PBRMaterialDefines();
  44338. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44339. if (effect.isReady()) {
  44340. if (onCompiled) {
  44341. onCompiled(this);
  44342. }
  44343. }
  44344. else {
  44345. effect.onCompileObservable.add(function () {
  44346. if (onCompiled) {
  44347. onCompiled(_this);
  44348. }
  44349. });
  44350. }
  44351. };
  44352. /**
  44353. * Initializes the uniform buffer layout for the shader.
  44354. */
  44355. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44356. // Order is important !
  44357. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44358. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44359. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44360. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44361. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44362. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44363. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44364. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44365. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44366. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44367. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44368. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44369. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44370. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44371. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44372. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44373. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44374. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44375. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44376. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44377. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44378. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44379. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44380. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44381. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44382. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44383. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44384. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44385. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44386. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44387. this._uniformBuffer.addUniform("pointSize", 1);
  44388. this._uniformBuffer.create();
  44389. };
  44390. /**
  44391. * Unbinds the textures.
  44392. */
  44393. PBRBaseMaterial.prototype.unbind = function () {
  44394. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44395. this._uniformBuffer.setTexture("reflectionSampler", null);
  44396. }
  44397. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44398. this._uniformBuffer.setTexture("refractionSampler", null);
  44399. }
  44400. _super.prototype.unbind.call(this);
  44401. };
  44402. /**
  44403. * Binds the submesh data.
  44404. * @param world - The world matrix.
  44405. * @param mesh - The BJS mesh.
  44406. * @param subMesh - A submesh of the BJS mesh.
  44407. */
  44408. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44409. var scene = this.getScene();
  44410. var defines = subMesh._materialDefines;
  44411. if (!defines) {
  44412. return;
  44413. }
  44414. var effect = subMesh.effect;
  44415. if (!effect) {
  44416. return;
  44417. }
  44418. this._activeEffect = effect;
  44419. // Matrices
  44420. this.bindOnlyWorldMatrix(world);
  44421. // Normal Matrix
  44422. if (defines.OBJECTSPACE_NORMALMAP) {
  44423. world.toNormalMatrix(this._normalMatrix);
  44424. this.bindOnlyNormalMatrix(this._normalMatrix);
  44425. }
  44426. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44427. // Bones
  44428. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44429. var reflectionTexture = null;
  44430. if (mustRebind) {
  44431. this._uniformBuffer.bindToEffect(effect, "Material");
  44432. this.bindViewProjection(effect);
  44433. reflectionTexture = this._getReflectionTexture();
  44434. var refractionTexture = this._getRefractionTexture();
  44435. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44436. // Texture uniforms
  44437. if (scene.texturesEnabled) {
  44438. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44439. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44440. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44441. }
  44442. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44443. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44444. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44445. }
  44446. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44447. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44448. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44449. }
  44450. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44451. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44452. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44453. if (reflectionTexture.boundingBoxSize) {
  44454. var cubeTexture = reflectionTexture;
  44455. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44456. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44457. }
  44458. var polynomials = reflectionTexture.sphericalPolynomial;
  44459. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44460. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44461. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44462. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44463. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44464. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44465. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44466. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44467. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44468. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44469. }
  44470. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44471. }
  44472. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44473. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44474. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44475. }
  44476. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44477. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44478. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44479. }
  44480. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44481. if (this._metallicTexture) {
  44482. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44484. }
  44485. else if (this._reflectivityTexture) {
  44486. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44487. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44488. }
  44489. if (this._microSurfaceTexture) {
  44490. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44491. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44492. }
  44493. }
  44494. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44495. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44496. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44497. if (scene._mirroredCameraPosition) {
  44498. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44499. }
  44500. else {
  44501. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44502. }
  44503. }
  44504. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44505. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44506. var depth = 1.0;
  44507. if (!refractionTexture.isCube) {
  44508. if (refractionTexture.depth) {
  44509. depth = refractionTexture.depth;
  44510. }
  44511. }
  44512. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44513. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44514. }
  44515. }
  44516. // Point size
  44517. if (this.pointsCloud) {
  44518. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44519. }
  44520. // Colors
  44521. if (defines.METALLICWORKFLOW) {
  44522. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44523. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44524. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44525. }
  44526. else {
  44527. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44528. }
  44529. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44530. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44531. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44532. // Misc
  44533. this._lightingInfos.x = this._directIntensity;
  44534. this._lightingInfos.y = this._emissiveIntensity;
  44535. this._lightingInfos.z = this._environmentIntensity;
  44536. this._lightingInfos.w = this._specularIntensity;
  44537. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44538. }
  44539. // Textures
  44540. if (scene.texturesEnabled) {
  44541. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44542. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44543. }
  44544. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44545. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44546. }
  44547. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44548. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44549. }
  44550. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44551. if (defines.LODBASEDMICROSFURACE) {
  44552. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44553. }
  44554. else {
  44555. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44556. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44557. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44558. }
  44559. }
  44560. if (defines.ENVIRONMENTBRDF) {
  44561. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44562. }
  44563. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44564. if (defines.LODBASEDMICROSFURACE) {
  44565. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44566. }
  44567. else {
  44568. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44569. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44570. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44571. }
  44572. }
  44573. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44574. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44575. }
  44576. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44577. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44578. }
  44579. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44580. if (this._metallicTexture) {
  44581. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44582. }
  44583. else if (this._reflectivityTexture) {
  44584. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44585. }
  44586. if (this._microSurfaceTexture) {
  44587. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44588. }
  44589. }
  44590. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44591. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44592. }
  44593. }
  44594. // Clip plane
  44595. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44596. // Colors
  44597. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44598. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44599. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44600. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44601. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44602. }
  44603. if (mustRebind || !this.isFrozen) {
  44604. // Lights
  44605. if (scene.lightsEnabled && !this._disableLighting) {
  44606. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44607. }
  44608. // View
  44609. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44610. this.bindView(effect);
  44611. }
  44612. // Fog
  44613. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44614. // Morph targets
  44615. if (defines.NUM_MORPH_INFLUENCERS) {
  44616. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44617. }
  44618. // image processing
  44619. this._imageProcessingConfiguration.bind(this._activeEffect);
  44620. // Log. depth
  44621. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44622. }
  44623. this._uniformBuffer.update();
  44624. this._afterBind(mesh, this._activeEffect);
  44625. };
  44626. /**
  44627. * Returns the animatable textures.
  44628. * @returns - Array of animatable textures.
  44629. */
  44630. PBRBaseMaterial.prototype.getAnimatables = function () {
  44631. var results = [];
  44632. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44633. results.push(this._albedoTexture);
  44634. }
  44635. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44636. results.push(this._ambientTexture);
  44637. }
  44638. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44639. results.push(this._opacityTexture);
  44640. }
  44641. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44642. results.push(this._reflectionTexture);
  44643. }
  44644. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44645. results.push(this._emissiveTexture);
  44646. }
  44647. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44648. results.push(this._metallicTexture);
  44649. }
  44650. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44651. results.push(this._reflectivityTexture);
  44652. }
  44653. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44654. results.push(this._bumpTexture);
  44655. }
  44656. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44657. results.push(this._lightmapTexture);
  44658. }
  44659. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44660. results.push(this._refractionTexture);
  44661. }
  44662. return results;
  44663. };
  44664. /**
  44665. * Returns the texture used for reflections.
  44666. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44667. */
  44668. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44669. if (this._reflectionTexture) {
  44670. return this._reflectionTexture;
  44671. }
  44672. return this.getScene().environmentTexture;
  44673. };
  44674. /**
  44675. * Returns the texture used for refraction or null if none is used.
  44676. * @returns - Refection texture if present. If no refraction texture and refraction
  44677. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44678. */
  44679. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44680. if (this._refractionTexture) {
  44681. return this._refractionTexture;
  44682. }
  44683. if (this._linkRefractionWithTransparency) {
  44684. return this.getScene().environmentTexture;
  44685. }
  44686. return null;
  44687. };
  44688. /**
  44689. * Disposes the resources of the material.
  44690. * @param forceDisposeEffect - Forces the disposal of effects.
  44691. * @param forceDisposeTextures - Forces the disposal of all textures.
  44692. */
  44693. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44694. if (forceDisposeTextures) {
  44695. if (this._albedoTexture) {
  44696. this._albedoTexture.dispose();
  44697. }
  44698. if (this._ambientTexture) {
  44699. this._ambientTexture.dispose();
  44700. }
  44701. if (this._opacityTexture) {
  44702. this._opacityTexture.dispose();
  44703. }
  44704. if (this._reflectionTexture) {
  44705. this._reflectionTexture.dispose();
  44706. }
  44707. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44708. this._environmentBRDFTexture.dispose();
  44709. }
  44710. if (this._emissiveTexture) {
  44711. this._emissiveTexture.dispose();
  44712. }
  44713. if (this._metallicTexture) {
  44714. this._metallicTexture.dispose();
  44715. }
  44716. if (this._reflectivityTexture) {
  44717. this._reflectivityTexture.dispose();
  44718. }
  44719. if (this._bumpTexture) {
  44720. this._bumpTexture.dispose();
  44721. }
  44722. if (this._lightmapTexture) {
  44723. this._lightmapTexture.dispose();
  44724. }
  44725. if (this._refractionTexture) {
  44726. this._refractionTexture.dispose();
  44727. }
  44728. }
  44729. this._renderTargets.dispose();
  44730. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44731. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44732. }
  44733. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44734. };
  44735. /**
  44736. * Stores the reflectivity values based on metallic roughness workflow.
  44737. */
  44738. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44739. __decorate([
  44740. BABYLON.serializeAsImageProcessingConfiguration()
  44741. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44742. __decorate([
  44743. BABYLON.serialize()
  44744. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44745. __decorate([
  44746. BABYLON.serialize()
  44747. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44748. return PBRBaseMaterial;
  44749. }(BABYLON.PushMaterial));
  44750. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44751. })(BABYLON || (BABYLON = {}));
  44752. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44753. var BABYLON;
  44754. (function (BABYLON) {
  44755. /**
  44756. * The Physically based simple base material of BJS.
  44757. *
  44758. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44759. * It is used as the base class for both the specGloss and metalRough conventions.
  44760. */
  44761. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44762. __extends(PBRBaseSimpleMaterial, _super);
  44763. /**
  44764. * Instantiates a new PBRMaterial instance.
  44765. *
  44766. * @param name The material name
  44767. * @param scene The scene the material will be use in.
  44768. */
  44769. function PBRBaseSimpleMaterial(name, scene) {
  44770. var _this = _super.call(this, name, scene) || this;
  44771. /**
  44772. * Number of Simultaneous lights allowed on the material.
  44773. */
  44774. _this.maxSimultaneousLights = 4;
  44775. /**
  44776. * If sets to true, disables all the lights affecting the material.
  44777. */
  44778. _this.disableLighting = false;
  44779. /**
  44780. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44781. */
  44782. _this.invertNormalMapX = false;
  44783. /**
  44784. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44785. */
  44786. _this.invertNormalMapY = false;
  44787. /**
  44788. * Emissivie color used to self-illuminate the model.
  44789. */
  44790. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44791. /**
  44792. * Occlusion Channel Strenght.
  44793. */
  44794. _this.occlusionStrength = 1.0;
  44795. _this.useLightmapAsShadowmap = false;
  44796. _this._useAlphaFromAlbedoTexture = true;
  44797. _this._useAmbientInGrayScale = true;
  44798. return _this;
  44799. }
  44800. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44801. /**
  44802. * Gets the current double sided mode.
  44803. */
  44804. get: function () {
  44805. return this._twoSidedLighting;
  44806. },
  44807. /**
  44808. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44809. */
  44810. set: function (value) {
  44811. if (this._twoSidedLighting === value) {
  44812. return;
  44813. }
  44814. this._twoSidedLighting = value;
  44815. this.backFaceCulling = !value;
  44816. this._markAllSubMeshesAsTexturesDirty();
  44817. },
  44818. enumerable: true,
  44819. configurable: true
  44820. });
  44821. /**
  44822. * Return the active textures of the material.
  44823. */
  44824. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44825. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44826. if (this.environmentTexture) {
  44827. activeTextures.push(this.environmentTexture);
  44828. }
  44829. if (this.normalTexture) {
  44830. activeTextures.push(this.normalTexture);
  44831. }
  44832. if (this.emissiveTexture) {
  44833. activeTextures.push(this.emissiveTexture);
  44834. }
  44835. if (this.occlusionTexture) {
  44836. activeTextures.push(this.occlusionTexture);
  44837. }
  44838. if (this.lightmapTexture) {
  44839. activeTextures.push(this.lightmapTexture);
  44840. }
  44841. return activeTextures;
  44842. };
  44843. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44844. if (_super.prototype.hasTexture.call(this, texture)) {
  44845. return true;
  44846. }
  44847. if (this.lightmapTexture === texture) {
  44848. return true;
  44849. }
  44850. return false;
  44851. };
  44852. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44853. return "PBRBaseSimpleMaterial";
  44854. };
  44855. __decorate([
  44856. BABYLON.serialize(),
  44857. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44858. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44859. __decorate([
  44860. BABYLON.serialize(),
  44861. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44862. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44863. __decorate([
  44864. BABYLON.serializeAsTexture(),
  44865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44866. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44867. __decorate([
  44868. BABYLON.serialize(),
  44869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44870. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44871. __decorate([
  44872. BABYLON.serialize(),
  44873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44874. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44875. __decorate([
  44876. BABYLON.serializeAsTexture(),
  44877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44878. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44879. __decorate([
  44880. BABYLON.serializeAsColor3("emissive"),
  44881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44882. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44883. __decorate([
  44884. BABYLON.serializeAsTexture(),
  44885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44886. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44887. __decorate([
  44888. BABYLON.serialize(),
  44889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44890. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44891. __decorate([
  44892. BABYLON.serializeAsTexture(),
  44893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44894. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44895. __decorate([
  44896. BABYLON.serialize(),
  44897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44898. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44899. __decorate([
  44900. BABYLON.serialize()
  44901. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44902. __decorate([
  44903. BABYLON.serializeAsTexture(),
  44904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44905. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44906. __decorate([
  44907. BABYLON.serialize(),
  44908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44909. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44910. return PBRBaseSimpleMaterial;
  44911. }(BABYLON.PBRBaseMaterial));
  44912. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44913. })(BABYLON || (BABYLON = {}));
  44914. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44915. var BABYLON;
  44916. (function (BABYLON) {
  44917. /**
  44918. * The Physically based material of BJS.
  44919. *
  44920. * This offers the main features of a standard PBR material.
  44921. * For more information, please refer to the documentation :
  44922. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44923. */
  44924. var PBRMaterial = /** @class */ (function (_super) {
  44925. __extends(PBRMaterial, _super);
  44926. /**
  44927. * Instantiates a new PBRMaterial instance.
  44928. *
  44929. * @param name The material name
  44930. * @param scene The scene the material will be use in.
  44931. */
  44932. function PBRMaterial(name, scene) {
  44933. var _this = _super.call(this, name, scene) || this;
  44934. /**
  44935. * Intensity of the direct lights e.g. the four lights available in your scene.
  44936. * This impacts both the direct diffuse and specular highlights.
  44937. */
  44938. _this.directIntensity = 1.0;
  44939. /**
  44940. * Intensity of the emissive part of the material.
  44941. * This helps controlling the emissive effect without modifying the emissive color.
  44942. */
  44943. _this.emissiveIntensity = 1.0;
  44944. /**
  44945. * Intensity of the environment e.g. how much the environment will light the object
  44946. * either through harmonics for rough material or through the refelction for shiny ones.
  44947. */
  44948. _this.environmentIntensity = 1.0;
  44949. /**
  44950. * This is a special control allowing the reduction of the specular highlights coming from the
  44951. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44952. */
  44953. _this.specularIntensity = 1.0;
  44954. /**
  44955. * Debug Control allowing disabling the bump map on this material.
  44956. */
  44957. _this.disableBumpMap = false;
  44958. /**
  44959. * AKA Occlusion Texture Intensity in other nomenclature.
  44960. */
  44961. _this.ambientTextureStrength = 1.0;
  44962. /**
  44963. * The color of a material in ambient lighting.
  44964. */
  44965. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44966. /**
  44967. * AKA Diffuse Color in other nomenclature.
  44968. */
  44969. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44970. /**
  44971. * AKA Specular Color in other nomenclature.
  44972. */
  44973. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44974. /**
  44975. * The color reflected from the material.
  44976. */
  44977. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44978. /**
  44979. * The color emitted from the material.
  44980. */
  44981. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44982. /**
  44983. * AKA Glossiness in other nomenclature.
  44984. */
  44985. _this.microSurface = 1.0;
  44986. /**
  44987. * source material index of refraction (IOR)' / 'destination material IOR.
  44988. */
  44989. _this.indexOfRefraction = 0.66;
  44990. /**
  44991. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44992. */
  44993. _this.invertRefractionY = false;
  44994. /**
  44995. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44996. * Materials half opaque for instance using refraction could benefit from this control.
  44997. */
  44998. _this.linkRefractionWithTransparency = false;
  44999. _this.useLightmapAsShadowmap = false;
  45000. /**
  45001. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45002. */
  45003. _this.useAlphaFromAlbedoTexture = false;
  45004. /**
  45005. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45006. */
  45007. _this.forceAlphaTest = false;
  45008. /**
  45009. * Defines the alpha limits in alpha test mode.
  45010. */
  45011. _this.alphaCutOff = 0.4;
  45012. /**
  45013. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45014. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45015. */
  45016. _this.useSpecularOverAlpha = true;
  45017. /**
  45018. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45019. */
  45020. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45021. /**
  45022. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45023. */
  45024. _this.useRoughnessFromMetallicTextureAlpha = true;
  45025. /**
  45026. * Specifies if the metallic texture contains the roughness information in its green channel.
  45027. */
  45028. _this.useRoughnessFromMetallicTextureGreen = false;
  45029. /**
  45030. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45031. */
  45032. _this.useMetallnessFromMetallicTextureBlue = false;
  45033. /**
  45034. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45035. */
  45036. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45037. /**
  45038. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45039. */
  45040. _this.useAmbientInGrayScale = false;
  45041. /**
  45042. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45043. * The material will try to infer what glossiness each pixel should be.
  45044. */
  45045. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45046. /**
  45047. * BJS is using an harcoded light falloff based on a manually sets up range.
  45048. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45049. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45050. */
  45051. _this.usePhysicalLightFalloff = true;
  45052. /**
  45053. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45054. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45055. */
  45056. _this.useRadianceOverAlpha = true;
  45057. /**
  45058. * Allows using an object space normal map (instead of tangent space).
  45059. */
  45060. _this.useObjectSpaceNormalMap = false;
  45061. /**
  45062. * Allows using the bump map in parallax mode.
  45063. */
  45064. _this.useParallax = false;
  45065. /**
  45066. * Allows using the bump map in parallax occlusion mode.
  45067. */
  45068. _this.useParallaxOcclusion = false;
  45069. /**
  45070. * Controls the scale bias of the parallax mode.
  45071. */
  45072. _this.parallaxScaleBias = 0.05;
  45073. /**
  45074. * If sets to true, disables all the lights affecting the material.
  45075. */
  45076. _this.disableLighting = false;
  45077. /**
  45078. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45079. */
  45080. _this.forceIrradianceInFragment = false;
  45081. /**
  45082. * Number of Simultaneous lights allowed on the material.
  45083. */
  45084. _this.maxSimultaneousLights = 4;
  45085. /**
  45086. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45087. */
  45088. _this.invertNormalMapX = false;
  45089. /**
  45090. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45091. */
  45092. _this.invertNormalMapY = false;
  45093. /**
  45094. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45095. */
  45096. _this.twoSidedLighting = false;
  45097. /**
  45098. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45099. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45100. */
  45101. _this.useAlphaFresnel = false;
  45102. /**
  45103. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45104. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45105. */
  45106. _this.useLinearAlphaFresnel = false;
  45107. /**
  45108. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45109. * And/Or occlude the blended part.
  45110. */
  45111. _this.environmentBRDFTexture = null;
  45112. /**
  45113. * Force normal to face away from face.
  45114. */
  45115. _this.forceNormalForward = false;
  45116. /**
  45117. * Enables specular anti aliasing in the PBR shader.
  45118. * It will both interacts on the Geometry for analytical and IBL lighting.
  45119. * It also prefilter the roughness map based on the bump values.
  45120. */
  45121. _this.enableSpecularAntiAliasing = false;
  45122. /**
  45123. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45124. * makes the reflect vector face the model (under horizon).
  45125. */
  45126. _this.useHorizonOcclusion = true;
  45127. /**
  45128. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45129. * too much the area relying on ambient texture to define their ambient occlusion.
  45130. */
  45131. _this.useRadianceOcclusion = true;
  45132. /**
  45133. * If set to true, no lighting calculations will be applied.
  45134. */
  45135. _this.unlit = false;
  45136. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45137. return _this;
  45138. }
  45139. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45140. /**
  45141. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45142. */
  45143. get: function () {
  45144. return this._PBRMATERIAL_OPAQUE;
  45145. },
  45146. enumerable: true,
  45147. configurable: true
  45148. });
  45149. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45150. /**
  45151. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45152. */
  45153. get: function () {
  45154. return this._PBRMATERIAL_ALPHATEST;
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45160. /**
  45161. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45162. */
  45163. get: function () {
  45164. return this._PBRMATERIAL_ALPHABLEND;
  45165. },
  45166. enumerable: true,
  45167. configurable: true
  45168. });
  45169. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45170. /**
  45171. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45172. * They are also discarded below the alpha cutoff threshold to improve performances.
  45173. */
  45174. get: function () {
  45175. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45176. },
  45177. enumerable: true,
  45178. configurable: true
  45179. });
  45180. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45181. /**
  45182. * Gets the image processing configuration used either in this material.
  45183. */
  45184. get: function () {
  45185. return this._imageProcessingConfiguration;
  45186. },
  45187. /**
  45188. * Sets the Default image processing configuration used either in the this material.
  45189. *
  45190. * If sets to null, the scene one is in use.
  45191. */
  45192. set: function (value) {
  45193. this._attachImageProcessingConfiguration(value);
  45194. // Ensure the effect will be rebuilt.
  45195. this._markAllSubMeshesAsTexturesDirty();
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45201. /**
  45202. * Gets wether the color curves effect is enabled.
  45203. */
  45204. get: function () {
  45205. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45206. },
  45207. /**
  45208. * Sets wether the color curves effect is enabled.
  45209. */
  45210. set: function (value) {
  45211. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45217. /**
  45218. * Gets wether the color grading effect is enabled.
  45219. */
  45220. get: function () {
  45221. return this.imageProcessingConfiguration.colorGradingEnabled;
  45222. },
  45223. /**
  45224. * Gets wether the color grading effect is enabled.
  45225. */
  45226. set: function (value) {
  45227. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45233. /**
  45234. * Gets wether tonemapping is enabled or not.
  45235. */
  45236. get: function () {
  45237. return this._imageProcessingConfiguration.toneMappingEnabled;
  45238. },
  45239. /**
  45240. * Sets wether tonemapping is enabled or not
  45241. */
  45242. set: function (value) {
  45243. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. ;
  45249. ;
  45250. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45251. /**
  45252. * The camera exposure used on this material.
  45253. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45254. * This corresponds to a photographic exposure.
  45255. */
  45256. get: function () {
  45257. return this._imageProcessingConfiguration.exposure;
  45258. },
  45259. /**
  45260. * The camera exposure used on this material.
  45261. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45262. * This corresponds to a photographic exposure.
  45263. */
  45264. set: function (value) {
  45265. this._imageProcessingConfiguration.exposure = value;
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. ;
  45271. ;
  45272. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45273. /**
  45274. * Gets The camera contrast used on this material.
  45275. */
  45276. get: function () {
  45277. return this._imageProcessingConfiguration.contrast;
  45278. },
  45279. /**
  45280. * Sets The camera contrast used on this material.
  45281. */
  45282. set: function (value) {
  45283. this._imageProcessingConfiguration.contrast = value;
  45284. },
  45285. enumerable: true,
  45286. configurable: true
  45287. });
  45288. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45289. /**
  45290. * Gets the Color Grading 2D Lookup Texture.
  45291. */
  45292. get: function () {
  45293. return this._imageProcessingConfiguration.colorGradingTexture;
  45294. },
  45295. /**
  45296. * Sets the Color Grading 2D Lookup Texture.
  45297. */
  45298. set: function (value) {
  45299. this._imageProcessingConfiguration.colorGradingTexture = value;
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45305. /**
  45306. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45307. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45308. * 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;
  45309. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45310. */
  45311. get: function () {
  45312. return this._imageProcessingConfiguration.colorCurves;
  45313. },
  45314. /**
  45315. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45316. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45317. * 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;
  45318. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45319. */
  45320. set: function (value) {
  45321. this._imageProcessingConfiguration.colorCurves = value;
  45322. },
  45323. enumerable: true,
  45324. configurable: true
  45325. });
  45326. /**
  45327. * Returns the name of this material class.
  45328. */
  45329. PBRMaterial.prototype.getClassName = function () {
  45330. return "PBRMaterial";
  45331. };
  45332. /**
  45333. * Returns an array of the actively used textures.
  45334. * @returns - Array of BaseTextures
  45335. */
  45336. PBRMaterial.prototype.getActiveTextures = function () {
  45337. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45338. if (this._albedoTexture) {
  45339. activeTextures.push(this._albedoTexture);
  45340. }
  45341. if (this._ambientTexture) {
  45342. activeTextures.push(this._ambientTexture);
  45343. }
  45344. if (this._opacityTexture) {
  45345. activeTextures.push(this._opacityTexture);
  45346. }
  45347. if (this._reflectionTexture) {
  45348. activeTextures.push(this._reflectionTexture);
  45349. }
  45350. if (this._emissiveTexture) {
  45351. activeTextures.push(this._emissiveTexture);
  45352. }
  45353. if (this._reflectivityTexture) {
  45354. activeTextures.push(this._reflectivityTexture);
  45355. }
  45356. if (this._metallicTexture) {
  45357. activeTextures.push(this._metallicTexture);
  45358. }
  45359. if (this._microSurfaceTexture) {
  45360. activeTextures.push(this._microSurfaceTexture);
  45361. }
  45362. if (this._bumpTexture) {
  45363. activeTextures.push(this._bumpTexture);
  45364. }
  45365. if (this._lightmapTexture) {
  45366. activeTextures.push(this._lightmapTexture);
  45367. }
  45368. if (this._refractionTexture) {
  45369. activeTextures.push(this._refractionTexture);
  45370. }
  45371. return activeTextures;
  45372. };
  45373. /**
  45374. * Checks to see if a texture is used in the material.
  45375. * @param texture - Base texture to use.
  45376. * @returns - Boolean specifying if a texture is used in the material.
  45377. */
  45378. PBRMaterial.prototype.hasTexture = function (texture) {
  45379. if (_super.prototype.hasTexture.call(this, texture)) {
  45380. return true;
  45381. }
  45382. if (this._albedoTexture === texture) {
  45383. return true;
  45384. }
  45385. if (this._ambientTexture === texture) {
  45386. return true;
  45387. }
  45388. if (this._opacityTexture === texture) {
  45389. return true;
  45390. }
  45391. if (this._reflectionTexture === texture) {
  45392. return true;
  45393. }
  45394. if (this._reflectivityTexture === texture) {
  45395. return true;
  45396. }
  45397. if (this._metallicTexture === texture) {
  45398. return true;
  45399. }
  45400. if (this._microSurfaceTexture === texture) {
  45401. return true;
  45402. }
  45403. if (this._bumpTexture === texture) {
  45404. return true;
  45405. }
  45406. if (this._lightmapTexture === texture) {
  45407. return true;
  45408. }
  45409. if (this._refractionTexture === texture) {
  45410. return true;
  45411. }
  45412. return false;
  45413. };
  45414. /**
  45415. * Makes a duplicate of the current material.
  45416. * @param name - name to use for the new material.
  45417. */
  45418. PBRMaterial.prototype.clone = function (name) {
  45419. var _this = this;
  45420. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45421. clone.id = name;
  45422. clone.name = name;
  45423. return clone;
  45424. };
  45425. /**
  45426. * Serializes this PBR Material.
  45427. * @returns - An object with the serialized material.
  45428. */
  45429. PBRMaterial.prototype.serialize = function () {
  45430. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45431. serializationObject.customType = "BABYLON.PBRMaterial";
  45432. return serializationObject;
  45433. };
  45434. // Statics
  45435. /**
  45436. * Parses a PBR Material from a serialized object.
  45437. * @param source - Serialized object.
  45438. * @param scene - BJS scene instance.
  45439. * @param rootUrl - url for the scene object
  45440. * @returns - PBRMaterial
  45441. */
  45442. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45443. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45444. };
  45445. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45446. /**
  45447. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45448. */
  45449. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45450. /**
  45451. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45452. */
  45453. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45454. /**
  45455. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45456. * They are also discarded below the alpha cutoff threshold to improve performances.
  45457. */
  45458. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "directIntensity", void 0);
  45463. __decorate([
  45464. BABYLON.serialize(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45467. __decorate([
  45468. BABYLON.serialize(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45479. __decorate([
  45480. BABYLON.serializeAsTexture(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsTexture(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsTexture(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45494. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45495. __decorate([
  45496. BABYLON.serializeAsTexture(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45499. __decorate([
  45500. BABYLON.serializeAsTexture(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45503. __decorate([
  45504. BABYLON.serializeAsTexture(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45507. __decorate([
  45508. BABYLON.serializeAsTexture(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "metallic", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "roughness", void 0);
  45519. __decorate([
  45520. BABYLON.serializeAsTexture(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45523. __decorate([
  45524. BABYLON.serializeAsTexture(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45527. __decorate([
  45528. BABYLON.serializeAsTexture(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45530. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45531. __decorate([
  45532. BABYLON.serializeAsTexture(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45535. __decorate([
  45536. BABYLON.serializeAsColor3("ambient"),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "ambientColor", void 0);
  45539. __decorate([
  45540. BABYLON.serializeAsColor3("albedo"),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "albedoColor", void 0);
  45543. __decorate([
  45544. BABYLON.serializeAsColor3("reflectivity"),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45547. __decorate([
  45548. BABYLON.serializeAsColor3("reflection"),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45551. __decorate([
  45552. BABYLON.serializeAsColor3("emissive"),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "microSurface", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45578. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45582. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45586. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "useParallax", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45646. ], PBRMaterial.prototype, "disableLighting", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45654. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45667. __decorate([
  45668. BABYLON.serialize(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45675. __decorate([
  45676. BABYLON.serializeAsTexture(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45690. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45698. ], PBRMaterial.prototype, "unlit", void 0);
  45699. return PBRMaterial;
  45700. }(BABYLON.PBRBaseMaterial));
  45701. BABYLON.PBRMaterial = PBRMaterial;
  45702. })(BABYLON || (BABYLON = {}));
  45703. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45704. var BABYLON;
  45705. (function (BABYLON) {
  45706. /**
  45707. * The PBR material of BJS following the metal roughness convention.
  45708. *
  45709. * This fits to the PBR convention in the GLTF definition:
  45710. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45711. */
  45712. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45713. __extends(PBRMetallicRoughnessMaterial, _super);
  45714. /**
  45715. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45716. *
  45717. * @param name The material name
  45718. * @param scene The scene the material will be use in.
  45719. */
  45720. function PBRMetallicRoughnessMaterial(name, scene) {
  45721. var _this = _super.call(this, name, scene) || this;
  45722. _this._useRoughnessFromMetallicTextureAlpha = false;
  45723. _this._useRoughnessFromMetallicTextureGreen = true;
  45724. _this._useMetallnessFromMetallicTextureBlue = true;
  45725. _this.metallic = 1.0;
  45726. _this.roughness = 1.0;
  45727. return _this;
  45728. }
  45729. /**
  45730. * Return the currrent class name of the material.
  45731. */
  45732. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45733. return "PBRMetallicRoughnessMaterial";
  45734. };
  45735. /**
  45736. * Return the active textures of the material.
  45737. */
  45738. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45739. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45740. if (this.baseTexture) {
  45741. activeTextures.push(this.baseTexture);
  45742. }
  45743. if (this.metallicRoughnessTexture) {
  45744. activeTextures.push(this.metallicRoughnessTexture);
  45745. }
  45746. return activeTextures;
  45747. };
  45748. /**
  45749. * Checks to see if a texture is used in the material.
  45750. * @param texture - Base texture to use.
  45751. * @returns - Boolean specifying if a texture is used in the material.
  45752. */
  45753. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45754. if (_super.prototype.hasTexture.call(this, texture)) {
  45755. return true;
  45756. }
  45757. if (this.baseTexture === texture) {
  45758. return true;
  45759. }
  45760. if (this.metallicRoughnessTexture === texture) {
  45761. return true;
  45762. }
  45763. return false;
  45764. };
  45765. /**
  45766. * Makes a duplicate of the current material.
  45767. * @param name - name to use for the new material.
  45768. */
  45769. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45770. var _this = this;
  45771. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45772. clone.id = name;
  45773. clone.name = name;
  45774. return clone;
  45775. };
  45776. /**
  45777. * Serialize the material to a parsable JSON object.
  45778. */
  45779. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45780. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45781. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45782. return serializationObject;
  45783. };
  45784. /**
  45785. * Parses a JSON object correponding to the serialize function.
  45786. */
  45787. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45788. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45789. };
  45790. __decorate([
  45791. BABYLON.serializeAsColor3(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45793. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45794. __decorate([
  45795. BABYLON.serializeAsTexture(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45797. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45798. __decorate([
  45799. BABYLON.serialize(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45802. __decorate([
  45803. BABYLON.serialize(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45806. __decorate([
  45807. BABYLON.serializeAsTexture(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45809. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45810. return PBRMetallicRoughnessMaterial;
  45811. }(BABYLON.PBRBaseSimpleMaterial));
  45812. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45813. })(BABYLON || (BABYLON = {}));
  45814. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45815. var BABYLON;
  45816. (function (BABYLON) {
  45817. /**
  45818. * The PBR material of BJS following the specular glossiness convention.
  45819. *
  45820. * This fits to the PBR convention in the GLTF definition:
  45821. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45822. */
  45823. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45824. __extends(PBRSpecularGlossinessMaterial, _super);
  45825. /**
  45826. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45827. *
  45828. * @param name The material name
  45829. * @param scene The scene the material will be use in.
  45830. */
  45831. function PBRSpecularGlossinessMaterial(name, scene) {
  45832. var _this = _super.call(this, name, scene) || this;
  45833. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45834. return _this;
  45835. }
  45836. /**
  45837. * Return the currrent class name of the material.
  45838. */
  45839. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45840. return "PBRSpecularGlossinessMaterial";
  45841. };
  45842. /**
  45843. * Return the active textures of the material.
  45844. */
  45845. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45846. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45847. if (this.diffuseTexture) {
  45848. activeTextures.push(this.diffuseTexture);
  45849. }
  45850. if (this.specularGlossinessTexture) {
  45851. activeTextures.push(this.specularGlossinessTexture);
  45852. }
  45853. return activeTextures;
  45854. };
  45855. /**
  45856. * Checks to see if a texture is used in the material.
  45857. * @param texture - Base texture to use.
  45858. * @returns - Boolean specifying if a texture is used in the material.
  45859. */
  45860. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45861. if (_super.prototype.hasTexture.call(this, texture)) {
  45862. return true;
  45863. }
  45864. if (this.diffuseTexture === texture) {
  45865. return true;
  45866. }
  45867. if (this.specularGlossinessTexture === texture) {
  45868. return true;
  45869. }
  45870. return false;
  45871. };
  45872. /**
  45873. * Makes a duplicate of the current material.
  45874. * @param name - name to use for the new material.
  45875. */
  45876. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45877. var _this = this;
  45878. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45879. clone.id = name;
  45880. clone.name = name;
  45881. return clone;
  45882. };
  45883. /**
  45884. * Serialize the material to a parsable JSON object.
  45885. */
  45886. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45887. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45888. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45889. return serializationObject;
  45890. };
  45891. /**
  45892. * Parses a JSON object correponding to the serialize function.
  45893. */
  45894. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45895. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45896. };
  45897. __decorate([
  45898. BABYLON.serializeAsColor3("diffuse"),
  45899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45900. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45901. __decorate([
  45902. BABYLON.serializeAsTexture(),
  45903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45904. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45905. __decorate([
  45906. BABYLON.serializeAsColor3("specular"),
  45907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45908. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45909. __decorate([
  45910. BABYLON.serialize(),
  45911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45912. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45913. __decorate([
  45914. BABYLON.serializeAsTexture(),
  45915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45916. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45917. return PBRSpecularGlossinessMaterial;
  45918. }(BABYLON.PBRBaseSimpleMaterial));
  45919. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45920. })(BABYLON || (BABYLON = {}));
  45921. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45922. var BABYLON;
  45923. (function (BABYLON) {
  45924. BABYLON.CameraInputTypes = {};
  45925. var CameraInputsManager = /** @class */ (function () {
  45926. function CameraInputsManager(camera) {
  45927. this.attached = {};
  45928. this.camera = camera;
  45929. this.checkInputs = function () { };
  45930. }
  45931. /**
  45932. * Add an input method to a camera.
  45933. * builtin inputs example: camera.inputs.addGamepad();
  45934. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45935. * @param input camera input method
  45936. */
  45937. CameraInputsManager.prototype.add = function (input) {
  45938. var type = input.getSimpleName();
  45939. if (this.attached[type]) {
  45940. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45941. return;
  45942. }
  45943. this.attached[type] = input;
  45944. input.camera = this.camera;
  45945. //for checkInputs, we are dynamically creating a function
  45946. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45947. if (input.checkInputs) {
  45948. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45949. }
  45950. if (this.attachedElement) {
  45951. input.attachControl(this.attachedElement);
  45952. }
  45953. };
  45954. /**
  45955. * Remove a specific input method from a camera
  45956. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45957. * @param inputToRemove camera input method
  45958. */
  45959. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45960. for (var cam in this.attached) {
  45961. var input = this.attached[cam];
  45962. if (input === inputToRemove) {
  45963. input.detachControl(this.attachedElement);
  45964. input.camera = null;
  45965. delete this.attached[cam];
  45966. this.rebuildInputCheck();
  45967. }
  45968. }
  45969. };
  45970. CameraInputsManager.prototype.removeByType = function (inputType) {
  45971. for (var cam in this.attached) {
  45972. var input = this.attached[cam];
  45973. if (input.getClassName() === inputType) {
  45974. input.detachControl(this.attachedElement);
  45975. input.camera = null;
  45976. delete this.attached[cam];
  45977. this.rebuildInputCheck();
  45978. }
  45979. }
  45980. };
  45981. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45982. var current = this.checkInputs;
  45983. return function () {
  45984. current();
  45985. fn();
  45986. };
  45987. };
  45988. CameraInputsManager.prototype.attachInput = function (input) {
  45989. if (this.attachedElement) {
  45990. input.attachControl(this.attachedElement, this.noPreventDefault);
  45991. }
  45992. };
  45993. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45994. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45995. if (this.attachedElement) {
  45996. return;
  45997. }
  45998. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45999. this.attachedElement = element;
  46000. this.noPreventDefault = noPreventDefault;
  46001. for (var cam in this.attached) {
  46002. this.attached[cam].attachControl(element, noPreventDefault);
  46003. }
  46004. };
  46005. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46006. if (disconnect === void 0) { disconnect = false; }
  46007. if (this.attachedElement !== element) {
  46008. return;
  46009. }
  46010. for (var cam in this.attached) {
  46011. this.attached[cam].detachControl(element);
  46012. if (disconnect) {
  46013. this.attached[cam].camera = null;
  46014. }
  46015. }
  46016. this.attachedElement = null;
  46017. };
  46018. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46019. this.checkInputs = function () { };
  46020. for (var cam in this.attached) {
  46021. var input = this.attached[cam];
  46022. if (input.checkInputs) {
  46023. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46024. }
  46025. }
  46026. };
  46027. /**
  46028. * Remove all attached input methods from a camera
  46029. */
  46030. CameraInputsManager.prototype.clear = function () {
  46031. if (this.attachedElement) {
  46032. this.detachElement(this.attachedElement, true);
  46033. }
  46034. this.attached = {};
  46035. this.attachedElement = null;
  46036. this.checkInputs = function () { };
  46037. };
  46038. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46039. var inputs = {};
  46040. for (var cam in this.attached) {
  46041. var input = this.attached[cam];
  46042. var res = BABYLON.SerializationHelper.Serialize(input);
  46043. inputs[input.getClassName()] = res;
  46044. }
  46045. serializedCamera.inputsmgr = inputs;
  46046. };
  46047. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46048. var parsedInputs = parsedCamera.inputsmgr;
  46049. if (parsedInputs) {
  46050. this.clear();
  46051. for (var n in parsedInputs) {
  46052. var construct = BABYLON.CameraInputTypes[n];
  46053. if (construct) {
  46054. var parsedinput = parsedInputs[n];
  46055. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46056. this.add(input);
  46057. }
  46058. }
  46059. }
  46060. else {
  46061. //2016-03-08 this part is for managing backward compatibility
  46062. for (var n in this.attached) {
  46063. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46064. if (construct) {
  46065. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46066. this.remove(this.attached[n]);
  46067. this.add(input);
  46068. }
  46069. }
  46070. }
  46071. };
  46072. return CameraInputsManager;
  46073. }());
  46074. BABYLON.CameraInputsManager = CameraInputsManager;
  46075. })(BABYLON || (BABYLON = {}));
  46076. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46077. var BABYLON;
  46078. (function (BABYLON) {
  46079. var TargetCamera = /** @class */ (function (_super) {
  46080. __extends(TargetCamera, _super);
  46081. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46082. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46083. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46084. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46085. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46086. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46087. _this.speed = 2.0;
  46088. _this.noRotationConstraint = false;
  46089. _this.lockedTarget = null;
  46090. _this._currentTarget = BABYLON.Vector3.Zero();
  46091. _this._viewMatrix = BABYLON.Matrix.Zero();
  46092. _this._camMatrix = BABYLON.Matrix.Zero();
  46093. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46094. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46095. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46096. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46097. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46098. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46099. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46100. return _this;
  46101. }
  46102. TargetCamera.prototype.getFrontPosition = function (distance) {
  46103. this.getWorldMatrix();
  46104. var direction = this.getTarget().subtract(this.position);
  46105. direction.normalize();
  46106. direction.scaleInPlace(distance);
  46107. return this.globalPosition.add(direction);
  46108. };
  46109. TargetCamera.prototype._getLockedTargetPosition = function () {
  46110. if (!this.lockedTarget) {
  46111. return null;
  46112. }
  46113. if (this.lockedTarget.absolutePosition) {
  46114. this.lockedTarget.computeWorldMatrix();
  46115. }
  46116. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46117. };
  46118. TargetCamera.prototype.storeState = function () {
  46119. this._storedPosition = this.position.clone();
  46120. this._storedRotation = this.rotation.clone();
  46121. if (this.rotationQuaternion) {
  46122. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46123. }
  46124. return _super.prototype.storeState.call(this);
  46125. };
  46126. /**
  46127. * Restored camera state. You must call storeState() first
  46128. */
  46129. TargetCamera.prototype._restoreStateValues = function () {
  46130. if (!_super.prototype._restoreStateValues.call(this)) {
  46131. return false;
  46132. }
  46133. this.position = this._storedPosition.clone();
  46134. this.rotation = this._storedRotation.clone();
  46135. if (this.rotationQuaternion) {
  46136. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46137. }
  46138. this.cameraDirection.copyFromFloats(0, 0, 0);
  46139. this.cameraRotation.copyFromFloats(0, 0);
  46140. return true;
  46141. };
  46142. // Cache
  46143. TargetCamera.prototype._initCache = function () {
  46144. _super.prototype._initCache.call(this);
  46145. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46146. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46147. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46148. };
  46149. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46150. if (!ignoreParentClass) {
  46151. _super.prototype._updateCache.call(this);
  46152. }
  46153. var lockedTargetPosition = this._getLockedTargetPosition();
  46154. if (!lockedTargetPosition) {
  46155. this._cache.lockedTarget = null;
  46156. }
  46157. else {
  46158. if (!this._cache.lockedTarget) {
  46159. this._cache.lockedTarget = lockedTargetPosition.clone();
  46160. }
  46161. else {
  46162. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46163. }
  46164. }
  46165. this._cache.rotation.copyFrom(this.rotation);
  46166. if (this.rotationQuaternion)
  46167. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46168. };
  46169. // Synchronized
  46170. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46171. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46172. return false;
  46173. }
  46174. var lockedTargetPosition = this._getLockedTargetPosition();
  46175. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46176. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46177. };
  46178. // Methods
  46179. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46180. var engine = this.getEngine();
  46181. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46182. };
  46183. // Target
  46184. TargetCamera.prototype.setTarget = function (target) {
  46185. this.upVector.normalize();
  46186. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46187. this._camMatrix.invert();
  46188. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46189. var vDir = target.subtract(this.position);
  46190. if (vDir.x >= 0.0) {
  46191. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46192. }
  46193. else {
  46194. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46195. }
  46196. this.rotation.z = 0;
  46197. if (isNaN(this.rotation.x)) {
  46198. this.rotation.x = 0;
  46199. }
  46200. if (isNaN(this.rotation.y)) {
  46201. this.rotation.y = 0;
  46202. }
  46203. if (isNaN(this.rotation.z)) {
  46204. this.rotation.z = 0;
  46205. }
  46206. if (this.rotationQuaternion) {
  46207. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46208. }
  46209. };
  46210. /**
  46211. * Return the current target position of the camera. This value is expressed in local space.
  46212. */
  46213. TargetCamera.prototype.getTarget = function () {
  46214. return this._currentTarget;
  46215. };
  46216. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46217. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46218. };
  46219. TargetCamera.prototype._updatePosition = function () {
  46220. if (this.parent) {
  46221. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46222. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46223. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46224. return;
  46225. }
  46226. this.position.addInPlace(this.cameraDirection);
  46227. };
  46228. TargetCamera.prototype._checkInputs = function () {
  46229. var needToMove = this._decideIfNeedsToMove();
  46230. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46231. // Move
  46232. if (needToMove) {
  46233. this._updatePosition();
  46234. }
  46235. // Rotate
  46236. if (needToRotate) {
  46237. this.rotation.x += this.cameraRotation.x;
  46238. this.rotation.y += this.cameraRotation.y;
  46239. //rotate, if quaternion is set and rotation was used
  46240. if (this.rotationQuaternion) {
  46241. var len = this.rotation.lengthSquared();
  46242. if (len) {
  46243. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46244. }
  46245. }
  46246. if (!this.noRotationConstraint) {
  46247. var limit = (Math.PI / 2) * 0.95;
  46248. if (this.rotation.x > limit)
  46249. this.rotation.x = limit;
  46250. if (this.rotation.x < -limit)
  46251. this.rotation.x = -limit;
  46252. }
  46253. }
  46254. // Inertia
  46255. if (needToMove) {
  46256. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46257. this.cameraDirection.x = 0;
  46258. }
  46259. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46260. this.cameraDirection.y = 0;
  46261. }
  46262. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46263. this.cameraDirection.z = 0;
  46264. }
  46265. this.cameraDirection.scaleInPlace(this.inertia);
  46266. }
  46267. if (needToRotate) {
  46268. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46269. this.cameraRotation.x = 0;
  46270. }
  46271. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46272. this.cameraRotation.y = 0;
  46273. }
  46274. this.cameraRotation.scaleInPlace(this.inertia);
  46275. }
  46276. _super.prototype._checkInputs.call(this);
  46277. };
  46278. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46279. if (this.rotationQuaternion) {
  46280. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46281. }
  46282. else {
  46283. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46284. }
  46285. //update the up vector!
  46286. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46287. };
  46288. TargetCamera.prototype._getViewMatrix = function () {
  46289. if (this.lockedTarget) {
  46290. this.setTarget(this._getLockedTargetPosition());
  46291. }
  46292. // Compute
  46293. this._updateCameraRotationMatrix();
  46294. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46295. // Computing target and final matrix
  46296. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46297. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46298. return this._viewMatrix;
  46299. };
  46300. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46301. if (this.parent) {
  46302. var parentWorldMatrix = this.parent.getWorldMatrix();
  46303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46304. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46305. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46306. this._markSyncedWithParent();
  46307. }
  46308. else {
  46309. this._globalPosition.copyFrom(this.position);
  46310. this._globalCurrentTarget.copyFrom(target);
  46311. this._globalCurrentUpVector.copyFrom(up);
  46312. }
  46313. if (this.getScene().useRightHandedSystem) {
  46314. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46315. }
  46316. else {
  46317. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46318. }
  46319. };
  46320. /**
  46321. * @override
  46322. * Override Camera.createRigCamera
  46323. */
  46324. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46325. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46326. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46327. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46328. if (!this.rotationQuaternion) {
  46329. this.rotationQuaternion = new BABYLON.Quaternion();
  46330. }
  46331. rigCamera._cameraRigParams = {};
  46332. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46333. }
  46334. return rigCamera;
  46335. }
  46336. return null;
  46337. };
  46338. /**
  46339. * @override
  46340. * Override Camera._updateRigCameras
  46341. */
  46342. TargetCamera.prototype._updateRigCameras = function () {
  46343. var camLeft = this._rigCameras[0];
  46344. var camRight = this._rigCameras[1];
  46345. switch (this.cameraRigMode) {
  46346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46347. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46349. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46350. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46351. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46352. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46353. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46354. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46355. camLeft.setTarget(this.getTarget());
  46356. camRight.setTarget(this.getTarget());
  46357. break;
  46358. case BABYLON.Camera.RIG_MODE_VR:
  46359. if (camLeft.rotationQuaternion) {
  46360. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46361. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46362. }
  46363. else {
  46364. camLeft.rotation.copyFrom(this.rotation);
  46365. camRight.rotation.copyFrom(this.rotation);
  46366. }
  46367. camLeft.position.copyFrom(this.position);
  46368. camRight.position.copyFrom(this.position);
  46369. break;
  46370. }
  46371. _super.prototype._updateRigCameras.call(this);
  46372. };
  46373. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46374. if (!this._rigCamTransformMatrix) {
  46375. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46376. }
  46377. var target = this.getTarget();
  46378. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46379. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46380. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46381. };
  46382. TargetCamera.prototype.getClassName = function () {
  46383. return "TargetCamera";
  46384. };
  46385. __decorate([
  46386. BABYLON.serializeAsVector3()
  46387. ], TargetCamera.prototype, "rotation", void 0);
  46388. __decorate([
  46389. BABYLON.serialize()
  46390. ], TargetCamera.prototype, "speed", void 0);
  46391. __decorate([
  46392. BABYLON.serializeAsMeshReference("lockedTargetId")
  46393. ], TargetCamera.prototype, "lockedTarget", void 0);
  46394. return TargetCamera;
  46395. }(BABYLON.Camera));
  46396. BABYLON.TargetCamera = TargetCamera;
  46397. })(BABYLON || (BABYLON = {}));
  46398. //# sourceMappingURL=babylon.targetCamera.js.map
  46399. var BABYLON;
  46400. (function (BABYLON) {
  46401. var FreeCameraMouseInput = /** @class */ (function () {
  46402. function FreeCameraMouseInput(touchEnabled) {
  46403. if (touchEnabled === void 0) { touchEnabled = true; }
  46404. this.touchEnabled = touchEnabled;
  46405. this.buttons = [0, 1, 2];
  46406. this.angularSensibility = 2000.0;
  46407. this.previousPosition = null;
  46408. }
  46409. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46410. var _this = this;
  46411. var engine = this.camera.getEngine();
  46412. if (!this._pointerInput) {
  46413. this._pointerInput = function (p, s) {
  46414. var evt = p.event;
  46415. if (engine.isInVRExclusivePointerMode) {
  46416. return;
  46417. }
  46418. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46419. return;
  46420. }
  46421. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46422. return;
  46423. }
  46424. var srcElement = (evt.srcElement || evt.target);
  46425. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46426. try {
  46427. srcElement.setPointerCapture(evt.pointerId);
  46428. }
  46429. catch (e) {
  46430. //Nothing to do with the error. Execution will continue.
  46431. }
  46432. _this.previousPosition = {
  46433. x: evt.clientX,
  46434. y: evt.clientY
  46435. };
  46436. if (!noPreventDefault) {
  46437. evt.preventDefault();
  46438. element.focus();
  46439. }
  46440. }
  46441. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46442. try {
  46443. srcElement.releasePointerCapture(evt.pointerId);
  46444. }
  46445. catch (e) {
  46446. //Nothing to do with the error.
  46447. }
  46448. _this.previousPosition = null;
  46449. if (!noPreventDefault) {
  46450. evt.preventDefault();
  46451. }
  46452. }
  46453. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46454. if (!_this.previousPosition || engine.isPointerLock) {
  46455. return;
  46456. }
  46457. var offsetX = evt.clientX - _this.previousPosition.x;
  46458. if (_this.camera.getScene().useRightHandedSystem)
  46459. offsetX *= -1;
  46460. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46461. offsetX *= -1;
  46462. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46463. var offsetY = evt.clientY - _this.previousPosition.y;
  46464. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46465. _this.previousPosition = {
  46466. x: evt.clientX,
  46467. y: evt.clientY
  46468. };
  46469. if (!noPreventDefault) {
  46470. evt.preventDefault();
  46471. }
  46472. }
  46473. };
  46474. }
  46475. this._onMouseMove = function (evt) {
  46476. if (!engine.isPointerLock) {
  46477. return;
  46478. }
  46479. if (engine.isInVRExclusivePointerMode) {
  46480. return;
  46481. }
  46482. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46483. if (_this.camera.getScene().useRightHandedSystem)
  46484. offsetX *= -1;
  46485. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46486. offsetX *= -1;
  46487. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46488. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46489. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46490. _this.previousPosition = null;
  46491. if (!noPreventDefault) {
  46492. evt.preventDefault();
  46493. }
  46494. };
  46495. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46496. element.addEventListener("mousemove", this._onMouseMove, false);
  46497. };
  46498. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46499. if (this._observer && element) {
  46500. this.camera.getScene().onPointerObservable.remove(this._observer);
  46501. if (this._onMouseMove) {
  46502. element.removeEventListener("mousemove", this._onMouseMove);
  46503. }
  46504. this._observer = null;
  46505. this._onMouseMove = null;
  46506. this.previousPosition = null;
  46507. }
  46508. };
  46509. FreeCameraMouseInput.prototype.getClassName = function () {
  46510. return "FreeCameraMouseInput";
  46511. };
  46512. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46513. return "mouse";
  46514. };
  46515. __decorate([
  46516. BABYLON.serialize()
  46517. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46518. __decorate([
  46519. BABYLON.serialize()
  46520. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46521. return FreeCameraMouseInput;
  46522. }());
  46523. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46524. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46525. })(BABYLON || (BABYLON = {}));
  46526. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46527. var BABYLON;
  46528. (function (BABYLON) {
  46529. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46530. function FreeCameraKeyboardMoveInput() {
  46531. this._keys = new Array();
  46532. this.keysUp = [38];
  46533. this.keysDown = [40];
  46534. this.keysLeft = [37];
  46535. this.keysRight = [39];
  46536. }
  46537. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46538. var _this = this;
  46539. if (this._onCanvasBlurObserver) {
  46540. return;
  46541. }
  46542. this._scene = this.camera.getScene();
  46543. this._engine = this._scene.getEngine();
  46544. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46545. _this._keys = [];
  46546. });
  46547. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46548. var evt = info.event;
  46549. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46550. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46551. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46552. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46553. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46554. var index = _this._keys.indexOf(evt.keyCode);
  46555. if (index === -1) {
  46556. _this._keys.push(evt.keyCode);
  46557. }
  46558. if (!noPreventDefault) {
  46559. evt.preventDefault();
  46560. }
  46561. }
  46562. }
  46563. else {
  46564. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46565. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46566. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46567. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46568. var index = _this._keys.indexOf(evt.keyCode);
  46569. if (index >= 0) {
  46570. _this._keys.splice(index, 1);
  46571. }
  46572. if (!noPreventDefault) {
  46573. evt.preventDefault();
  46574. }
  46575. }
  46576. }
  46577. });
  46578. };
  46579. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46580. if (this._scene) {
  46581. if (this._onKeyboardObserver) {
  46582. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46583. }
  46584. if (this._onCanvasBlurObserver) {
  46585. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46586. }
  46587. this._onKeyboardObserver = null;
  46588. this._onCanvasBlurObserver = null;
  46589. }
  46590. this._keys = [];
  46591. };
  46592. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46593. if (this._onKeyboardObserver) {
  46594. var camera = this.camera;
  46595. // Keyboard
  46596. for (var index = 0; index < this._keys.length; index++) {
  46597. var keyCode = this._keys[index];
  46598. var speed = camera._computeLocalCameraSpeed();
  46599. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46600. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46601. }
  46602. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46603. camera._localDirection.copyFromFloats(0, 0, speed);
  46604. }
  46605. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46606. camera._localDirection.copyFromFloats(speed, 0, 0);
  46607. }
  46608. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46609. camera._localDirection.copyFromFloats(0, 0, -speed);
  46610. }
  46611. if (camera.getScene().useRightHandedSystem) {
  46612. camera._localDirection.z *= -1;
  46613. }
  46614. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46615. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46616. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46617. }
  46618. }
  46619. };
  46620. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46621. return "FreeCameraKeyboardMoveInput";
  46622. };
  46623. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46624. this._keys = [];
  46625. };
  46626. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46627. return "keyboard";
  46628. };
  46629. __decorate([
  46630. BABYLON.serialize()
  46631. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46632. __decorate([
  46633. BABYLON.serialize()
  46634. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46635. __decorate([
  46636. BABYLON.serialize()
  46637. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46638. __decorate([
  46639. BABYLON.serialize()
  46640. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46641. return FreeCameraKeyboardMoveInput;
  46642. }());
  46643. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46644. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46645. })(BABYLON || (BABYLON = {}));
  46646. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46647. var BABYLON;
  46648. (function (BABYLON) {
  46649. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46650. __extends(FreeCameraInputsManager, _super);
  46651. function FreeCameraInputsManager(camera) {
  46652. return _super.call(this, camera) || this;
  46653. }
  46654. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46655. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46656. return this;
  46657. };
  46658. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46659. if (touchEnabled === void 0) { touchEnabled = true; }
  46660. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46661. return this;
  46662. };
  46663. FreeCameraInputsManager.prototype.addGamepad = function () {
  46664. this.add(new BABYLON.FreeCameraGamepadInput());
  46665. return this;
  46666. };
  46667. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46668. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46669. return this;
  46670. };
  46671. FreeCameraInputsManager.prototype.addTouch = function () {
  46672. this.add(new BABYLON.FreeCameraTouchInput());
  46673. return this;
  46674. };
  46675. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46676. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46677. return this;
  46678. };
  46679. return FreeCameraInputsManager;
  46680. }(BABYLON.CameraInputsManager));
  46681. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46682. })(BABYLON || (BABYLON = {}));
  46683. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46684. var BABYLON;
  46685. (function (BABYLON) {
  46686. var FreeCamera = /** @class */ (function (_super) {
  46687. __extends(FreeCamera, _super);
  46688. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46689. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46690. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46691. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46692. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46693. _this.checkCollisions = false;
  46694. _this.applyGravity = false;
  46695. _this._needMoveForGravity = false;
  46696. _this._oldPosition = BABYLON.Vector3.Zero();
  46697. _this._diffPosition = BABYLON.Vector3.Zero();
  46698. _this._newPosition = BABYLON.Vector3.Zero();
  46699. // Collisions
  46700. _this._collisionMask = -1;
  46701. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46702. if (collidedMesh === void 0) { collidedMesh = null; }
  46703. //TODO move this to the collision coordinator!
  46704. if (_this.getScene().workerCollisions)
  46705. newPosition.multiplyInPlace(_this._collider._radius);
  46706. var updatePosition = function (newPos) {
  46707. _this._newPosition.copyFrom(newPos);
  46708. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46709. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46710. _this.position.addInPlace(_this._diffPosition);
  46711. if (_this.onCollide && collidedMesh) {
  46712. _this.onCollide(collidedMesh);
  46713. }
  46714. }
  46715. };
  46716. updatePosition(newPosition);
  46717. };
  46718. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46719. _this.inputs.addKeyboard().addMouse();
  46720. return _this;
  46721. }
  46722. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46723. //-- begin properties for backward compatibility for inputs
  46724. /**
  46725. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46726. * Higher values reduce sensitivity.
  46727. */
  46728. get: function () {
  46729. var mouse = this.inputs.attached["mouse"];
  46730. if (mouse)
  46731. return mouse.angularSensibility;
  46732. return 0;
  46733. },
  46734. /**
  46735. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46736. * Higher values reduce sensitivity.
  46737. */
  46738. set: function (value) {
  46739. var mouse = this.inputs.attached["mouse"];
  46740. if (mouse)
  46741. mouse.angularSensibility = value;
  46742. },
  46743. enumerable: true,
  46744. configurable: true
  46745. });
  46746. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46747. get: function () {
  46748. var keyboard = this.inputs.attached["keyboard"];
  46749. if (keyboard)
  46750. return keyboard.keysUp;
  46751. return [];
  46752. },
  46753. set: function (value) {
  46754. var keyboard = this.inputs.attached["keyboard"];
  46755. if (keyboard)
  46756. keyboard.keysUp = value;
  46757. },
  46758. enumerable: true,
  46759. configurable: true
  46760. });
  46761. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46762. get: function () {
  46763. var keyboard = this.inputs.attached["keyboard"];
  46764. if (keyboard)
  46765. return keyboard.keysDown;
  46766. return [];
  46767. },
  46768. set: function (value) {
  46769. var keyboard = this.inputs.attached["keyboard"];
  46770. if (keyboard)
  46771. keyboard.keysDown = value;
  46772. },
  46773. enumerable: true,
  46774. configurable: true
  46775. });
  46776. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46777. get: function () {
  46778. var keyboard = this.inputs.attached["keyboard"];
  46779. if (keyboard)
  46780. return keyboard.keysLeft;
  46781. return [];
  46782. },
  46783. set: function (value) {
  46784. var keyboard = this.inputs.attached["keyboard"];
  46785. if (keyboard)
  46786. keyboard.keysLeft = value;
  46787. },
  46788. enumerable: true,
  46789. configurable: true
  46790. });
  46791. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46792. get: function () {
  46793. var keyboard = this.inputs.attached["keyboard"];
  46794. if (keyboard)
  46795. return keyboard.keysRight;
  46796. return [];
  46797. },
  46798. set: function (value) {
  46799. var keyboard = this.inputs.attached["keyboard"];
  46800. if (keyboard)
  46801. keyboard.keysRight = value;
  46802. },
  46803. enumerable: true,
  46804. configurable: true
  46805. });
  46806. // Controls
  46807. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46808. this.inputs.attachElement(element, noPreventDefault);
  46809. };
  46810. FreeCamera.prototype.detachControl = function (element) {
  46811. this.inputs.detachElement(element);
  46812. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46813. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46814. };
  46815. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46816. get: function () {
  46817. return this._collisionMask;
  46818. },
  46819. set: function (mask) {
  46820. this._collisionMask = !isNaN(mask) ? mask : -1;
  46821. },
  46822. enumerable: true,
  46823. configurable: true
  46824. });
  46825. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46826. var globalPosition;
  46827. if (this.parent) {
  46828. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46829. }
  46830. else {
  46831. globalPosition = this.position;
  46832. }
  46833. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46834. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46835. if (!this._collider) {
  46836. this._collider = new BABYLON.Collider();
  46837. }
  46838. this._collider._radius = this.ellipsoid;
  46839. this._collider.collisionMask = this._collisionMask;
  46840. //no need for clone, as long as gravity is not on.
  46841. var actualDisplacement = displacement;
  46842. //add gravity to the direction to prevent the dual-collision checking
  46843. if (this.applyGravity) {
  46844. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46845. actualDisplacement = displacement.add(this.getScene().gravity);
  46846. }
  46847. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46848. };
  46849. FreeCamera.prototype._checkInputs = function () {
  46850. if (!this._localDirection) {
  46851. this._localDirection = BABYLON.Vector3.Zero();
  46852. this._transformedDirection = BABYLON.Vector3.Zero();
  46853. }
  46854. this.inputs.checkInputs();
  46855. _super.prototype._checkInputs.call(this);
  46856. };
  46857. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46858. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46859. };
  46860. FreeCamera.prototype._updatePosition = function () {
  46861. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46862. this._collideWithWorld(this.cameraDirection);
  46863. }
  46864. else {
  46865. _super.prototype._updatePosition.call(this);
  46866. }
  46867. };
  46868. FreeCamera.prototype.dispose = function () {
  46869. this.inputs.clear();
  46870. _super.prototype.dispose.call(this);
  46871. };
  46872. FreeCamera.prototype.getClassName = function () {
  46873. return "FreeCamera";
  46874. };
  46875. __decorate([
  46876. BABYLON.serializeAsVector3()
  46877. ], FreeCamera.prototype, "ellipsoid", void 0);
  46878. __decorate([
  46879. BABYLON.serializeAsVector3()
  46880. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], FreeCamera.prototype, "checkCollisions", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], FreeCamera.prototype, "applyGravity", void 0);
  46887. return FreeCamera;
  46888. }(BABYLON.TargetCamera));
  46889. BABYLON.FreeCamera = FreeCamera;
  46890. })(BABYLON || (BABYLON = {}));
  46891. //# sourceMappingURL=babylon.freeCamera.js.map
  46892. var BABYLON;
  46893. (function (BABYLON) {
  46894. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46895. function ArcRotateCameraKeyboardMoveInput() {
  46896. this._keys = new Array();
  46897. this.keysUp = [38];
  46898. this.keysDown = [40];
  46899. this.keysLeft = [37];
  46900. this.keysRight = [39];
  46901. this.keysReset = [220];
  46902. this.panningSensibility = 50.0;
  46903. this.zoomingSensibility = 25.0;
  46904. this.useAltToZoom = true;
  46905. }
  46906. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46907. var _this = this;
  46908. if (this._onCanvasBlurObserver) {
  46909. return;
  46910. }
  46911. this._scene = this.camera.getScene();
  46912. this._engine = this._scene.getEngine();
  46913. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46914. _this._keys = [];
  46915. });
  46916. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46917. var evt = info.event;
  46918. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46919. _this._ctrlPressed = evt.ctrlKey;
  46920. _this._altPressed = evt.altKey;
  46921. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46922. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46923. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46924. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46925. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46926. var index = _this._keys.indexOf(evt.keyCode);
  46927. if (index === -1) {
  46928. _this._keys.push(evt.keyCode);
  46929. }
  46930. if (evt.preventDefault) {
  46931. if (!noPreventDefault) {
  46932. evt.preventDefault();
  46933. }
  46934. }
  46935. }
  46936. }
  46937. else {
  46938. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46939. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46940. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46941. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46942. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46943. var index = _this._keys.indexOf(evt.keyCode);
  46944. if (index >= 0) {
  46945. _this._keys.splice(index, 1);
  46946. }
  46947. if (evt.preventDefault) {
  46948. if (!noPreventDefault) {
  46949. evt.preventDefault();
  46950. }
  46951. }
  46952. }
  46953. }
  46954. });
  46955. };
  46956. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46957. if (this._scene) {
  46958. if (this._onKeyboardObserver) {
  46959. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46960. }
  46961. if (this._onCanvasBlurObserver) {
  46962. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46963. }
  46964. this._onKeyboardObserver = null;
  46965. this._onCanvasBlurObserver = null;
  46966. }
  46967. this._keys = [];
  46968. };
  46969. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46970. if (this._onKeyboardObserver) {
  46971. var camera = this.camera;
  46972. for (var index = 0; index < this._keys.length; index++) {
  46973. var keyCode = this._keys[index];
  46974. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46975. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46976. camera.inertialPanningX -= 1 / this.panningSensibility;
  46977. }
  46978. else {
  46979. camera.inertialAlphaOffset -= 0.01;
  46980. }
  46981. }
  46982. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46983. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46984. camera.inertialPanningY += 1 / this.panningSensibility;
  46985. }
  46986. else if (this._altPressed && this.useAltToZoom) {
  46987. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46988. }
  46989. else {
  46990. camera.inertialBetaOffset -= 0.01;
  46991. }
  46992. }
  46993. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46994. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46995. camera.inertialPanningX += 1 / this.panningSensibility;
  46996. }
  46997. else {
  46998. camera.inertialAlphaOffset += 0.01;
  46999. }
  47000. }
  47001. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47002. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47003. camera.inertialPanningY -= 1 / this.panningSensibility;
  47004. }
  47005. else if (this._altPressed && this.useAltToZoom) {
  47006. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47007. }
  47008. else {
  47009. camera.inertialBetaOffset += 0.01;
  47010. }
  47011. }
  47012. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47013. camera.restoreState();
  47014. }
  47015. }
  47016. }
  47017. };
  47018. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47019. return "ArcRotateCameraKeyboardMoveInput";
  47020. };
  47021. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47022. return "keyboard";
  47023. };
  47024. __decorate([
  47025. BABYLON.serialize()
  47026. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47027. __decorate([
  47028. BABYLON.serialize()
  47029. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47030. __decorate([
  47031. BABYLON.serialize()
  47032. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47033. __decorate([
  47034. BABYLON.serialize()
  47035. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47036. __decorate([
  47037. BABYLON.serialize()
  47038. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47039. __decorate([
  47040. BABYLON.serialize()
  47041. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47042. __decorate([
  47043. BABYLON.serialize()
  47044. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47045. __decorate([
  47046. BABYLON.serialize()
  47047. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47048. return ArcRotateCameraKeyboardMoveInput;
  47049. }());
  47050. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47051. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47052. })(BABYLON || (BABYLON = {}));
  47053. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47054. var BABYLON;
  47055. (function (BABYLON) {
  47056. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47057. function ArcRotateCameraMouseWheelInput() {
  47058. this.wheelPrecision = 3.0;
  47059. /**
  47060. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47061. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47062. */
  47063. this.wheelDeltaPercentage = 0;
  47064. }
  47065. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47066. var _this = this;
  47067. this._wheel = function (p, s) {
  47068. //sanity check - this should be a PointerWheel event.
  47069. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47070. return;
  47071. var event = p.event;
  47072. var delta = 0;
  47073. if (event.wheelDelta) {
  47074. if (_this.wheelDeltaPercentage) {
  47075. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47076. if (event.wheelDelta > 0) {
  47077. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47078. }
  47079. else {
  47080. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47081. }
  47082. }
  47083. else {
  47084. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47085. }
  47086. }
  47087. else if (event.detail) {
  47088. delta = -event.detail / _this.wheelPrecision;
  47089. }
  47090. if (delta)
  47091. _this.camera.inertialRadiusOffset += delta;
  47092. if (event.preventDefault) {
  47093. if (!noPreventDefault) {
  47094. event.preventDefault();
  47095. }
  47096. }
  47097. };
  47098. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47099. };
  47100. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47101. if (this._observer && element) {
  47102. this.camera.getScene().onPointerObservable.remove(this._observer);
  47103. this._observer = null;
  47104. this._wheel = null;
  47105. }
  47106. };
  47107. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47108. return "ArcRotateCameraMouseWheelInput";
  47109. };
  47110. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47111. return "mousewheel";
  47112. };
  47113. __decorate([
  47114. BABYLON.serialize()
  47115. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47116. __decorate([
  47117. BABYLON.serialize()
  47118. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47119. return ArcRotateCameraMouseWheelInput;
  47120. }());
  47121. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47122. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47123. })(BABYLON || (BABYLON = {}));
  47124. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47125. var BABYLON;
  47126. (function (BABYLON) {
  47127. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47128. function ArcRotateCameraPointersInput() {
  47129. this.buttons = [0, 1, 2];
  47130. this.angularSensibilityX = 1000.0;
  47131. this.angularSensibilityY = 1000.0;
  47132. this.pinchPrecision = 12.0;
  47133. /**
  47134. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47135. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47136. */
  47137. this.pinchDeltaPercentage = 0;
  47138. this.panningSensibility = 1000.0;
  47139. this.multiTouchPanning = true;
  47140. this.multiTouchPanAndZoom = true;
  47141. this._isPanClick = false;
  47142. this.pinchInwards = true;
  47143. }
  47144. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47145. var _this = this;
  47146. var engine = this.camera.getEngine();
  47147. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47148. var pointA = null;
  47149. var pointB = null;
  47150. var previousPinchSquaredDistance = 0;
  47151. var initialDistance = 0;
  47152. var twoFingerActivityCount = 0;
  47153. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47154. this._pointerInput = function (p, s) {
  47155. var evt = p.event;
  47156. var isTouch = p.event.pointerType === "touch";
  47157. if (engine.isInVRExclusivePointerMode) {
  47158. return;
  47159. }
  47160. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47161. return;
  47162. }
  47163. var srcElement = (evt.srcElement || evt.target);
  47164. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47165. try {
  47166. srcElement.setPointerCapture(evt.pointerId);
  47167. }
  47168. catch (e) {
  47169. //Nothing to do with the error. Execution will continue.
  47170. }
  47171. // Manage panning with pan button click
  47172. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47173. // manage pointers
  47174. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47175. if (pointA === null) {
  47176. pointA = cacheSoloPointer;
  47177. }
  47178. else if (pointB === null) {
  47179. pointB = cacheSoloPointer;
  47180. }
  47181. if (!noPreventDefault) {
  47182. evt.preventDefault();
  47183. element.focus();
  47184. }
  47185. }
  47186. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47187. _this.camera.restoreState();
  47188. }
  47189. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47190. try {
  47191. srcElement.releasePointerCapture(evt.pointerId);
  47192. }
  47193. catch (e) {
  47194. //Nothing to do with the error.
  47195. }
  47196. cacheSoloPointer = null;
  47197. previousPinchSquaredDistance = 0;
  47198. previousMultiTouchPanPosition.isPaning = false;
  47199. previousMultiTouchPanPosition.isPinching = false;
  47200. twoFingerActivityCount = 0;
  47201. initialDistance = 0;
  47202. if (!isTouch) {
  47203. pointB = null; // Mouse and pen are mono pointer
  47204. }
  47205. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47206. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47207. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47208. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47209. if (engine._badOS) {
  47210. pointA = pointB = null;
  47211. }
  47212. else {
  47213. //only remove the impacted pointer in case of multitouch allowing on most
  47214. //platforms switching from rotate to zoom and pan seamlessly.
  47215. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47216. pointA = pointB;
  47217. pointB = null;
  47218. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47219. }
  47220. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47221. pointB = null;
  47222. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47223. }
  47224. else {
  47225. pointA = pointB = null;
  47226. }
  47227. }
  47228. if (!noPreventDefault) {
  47229. evt.preventDefault();
  47230. }
  47231. }
  47232. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47233. if (!noPreventDefault) {
  47234. evt.preventDefault();
  47235. }
  47236. // One button down
  47237. if (pointA && pointB === null && cacheSoloPointer) {
  47238. if (_this.panningSensibility !== 0 &&
  47239. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47240. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47241. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47242. }
  47243. else {
  47244. var offsetX = evt.clientX - cacheSoloPointer.x;
  47245. var offsetY = evt.clientY - cacheSoloPointer.y;
  47246. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47247. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47248. }
  47249. cacheSoloPointer.x = evt.clientX;
  47250. cacheSoloPointer.y = evt.clientY;
  47251. }
  47252. // Two buttons down: pinch/pan
  47253. else if (pointA && pointB) {
  47254. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47255. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47256. ed.x = evt.clientX;
  47257. ed.y = evt.clientY;
  47258. var direction = _this.pinchInwards ? 1 : -1;
  47259. var distX = pointA.x - pointB.x;
  47260. var distY = pointA.y - pointB.y;
  47261. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47262. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47263. if (previousPinchSquaredDistance === 0) {
  47264. initialDistance = pinchDistance;
  47265. previousPinchSquaredDistance = pinchSquaredDistance;
  47266. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47267. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47268. return;
  47269. }
  47270. if (_this.multiTouchPanAndZoom) {
  47271. if (_this.pinchDeltaPercentage) {
  47272. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47273. }
  47274. else {
  47275. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47276. (_this.pinchPrecision *
  47277. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47278. direction);
  47279. }
  47280. if (_this.panningSensibility !== 0) {
  47281. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47282. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47283. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47284. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47285. previousMultiTouchPanPosition.x = pointersCenterX;
  47286. previousMultiTouchPanPosition.y = pointersCenterY;
  47287. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47288. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47289. }
  47290. }
  47291. else {
  47292. twoFingerActivityCount++;
  47293. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47294. if (_this.pinchDeltaPercentage) {
  47295. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47296. }
  47297. else {
  47298. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47299. (_this.pinchPrecision *
  47300. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47301. direction);
  47302. }
  47303. previousMultiTouchPanPosition.isPaning = false;
  47304. previousMultiTouchPanPosition.isPinching = true;
  47305. }
  47306. else {
  47307. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47308. if (!previousMultiTouchPanPosition.isPaning) {
  47309. previousMultiTouchPanPosition.isPaning = true;
  47310. previousMultiTouchPanPosition.isPinching = false;
  47311. previousMultiTouchPanPosition.x = ed.x;
  47312. previousMultiTouchPanPosition.y = ed.y;
  47313. return;
  47314. }
  47315. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47316. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47317. }
  47318. }
  47319. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47320. previousMultiTouchPanPosition.x = ed.x;
  47321. previousMultiTouchPanPosition.y = ed.y;
  47322. }
  47323. }
  47324. previousPinchSquaredDistance = pinchSquaredDistance;
  47325. }
  47326. }
  47327. };
  47328. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47329. this._onContextMenu = function (evt) {
  47330. evt.preventDefault();
  47331. };
  47332. if (!this.camera._useCtrlForPanning) {
  47333. element.addEventListener("contextmenu", this._onContextMenu, false);
  47334. }
  47335. this._onLostFocus = function () {
  47336. //this._keys = [];
  47337. pointA = pointB = null;
  47338. previousPinchSquaredDistance = 0;
  47339. previousMultiTouchPanPosition.isPaning = false;
  47340. previousMultiTouchPanPosition.isPinching = false;
  47341. twoFingerActivityCount = 0;
  47342. cacheSoloPointer = null;
  47343. initialDistance = 0;
  47344. };
  47345. this._onMouseMove = function (evt) {
  47346. if (!engine.isPointerLock) {
  47347. return;
  47348. }
  47349. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47350. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47351. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47352. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47353. if (!noPreventDefault) {
  47354. evt.preventDefault();
  47355. }
  47356. };
  47357. this._onGestureStart = function (e) {
  47358. if (window.MSGesture === undefined) {
  47359. return;
  47360. }
  47361. if (!_this._MSGestureHandler) {
  47362. _this._MSGestureHandler = new MSGesture();
  47363. _this._MSGestureHandler.target = element;
  47364. }
  47365. _this._MSGestureHandler.addPointer(e.pointerId);
  47366. };
  47367. this._onGesture = function (e) {
  47368. _this.camera.radius *= e.scale;
  47369. if (e.preventDefault) {
  47370. if (!noPreventDefault) {
  47371. e.stopPropagation();
  47372. e.preventDefault();
  47373. }
  47374. }
  47375. };
  47376. element.addEventListener("mousemove", this._onMouseMove, false);
  47377. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47378. element.addEventListener("MSGestureChange", this._onGesture, false);
  47379. BABYLON.Tools.RegisterTopRootEvents([
  47380. { name: "blur", handler: this._onLostFocus }
  47381. ]);
  47382. };
  47383. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47384. if (this._onLostFocus) {
  47385. BABYLON.Tools.UnregisterTopRootEvents([
  47386. { name: "blur", handler: this._onLostFocus }
  47387. ]);
  47388. }
  47389. if (element && this._observer) {
  47390. this.camera.getScene().onPointerObservable.remove(this._observer);
  47391. this._observer = null;
  47392. if (this._onContextMenu) {
  47393. element.removeEventListener("contextmenu", this._onContextMenu);
  47394. }
  47395. if (this._onMouseMove) {
  47396. element.removeEventListener("mousemove", this._onMouseMove);
  47397. }
  47398. if (this._onGestureStart) {
  47399. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47400. }
  47401. if (this._onGesture) {
  47402. element.removeEventListener("MSGestureChange", this._onGesture);
  47403. }
  47404. this._isPanClick = false;
  47405. this.pinchInwards = true;
  47406. this._onMouseMove = null;
  47407. this._onGestureStart = null;
  47408. this._onGesture = null;
  47409. this._MSGestureHandler = null;
  47410. this._onLostFocus = null;
  47411. this._onContextMenu = null;
  47412. }
  47413. };
  47414. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47415. return "ArcRotateCameraPointersInput";
  47416. };
  47417. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47418. return "pointers";
  47419. };
  47420. __decorate([
  47421. BABYLON.serialize()
  47422. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47423. __decorate([
  47424. BABYLON.serialize()
  47425. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47426. __decorate([
  47427. BABYLON.serialize()
  47428. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47429. __decorate([
  47430. BABYLON.serialize()
  47431. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47432. __decorate([
  47433. BABYLON.serialize()
  47434. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47435. __decorate([
  47436. BABYLON.serialize()
  47437. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47438. __decorate([
  47439. BABYLON.serialize()
  47440. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47441. __decorate([
  47442. BABYLON.serialize()
  47443. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47444. return ArcRotateCameraPointersInput;
  47445. }());
  47446. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47447. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47448. })(BABYLON || (BABYLON = {}));
  47449. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47450. var BABYLON;
  47451. (function (BABYLON) {
  47452. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47453. __extends(ArcRotateCameraInputsManager, _super);
  47454. function ArcRotateCameraInputsManager(camera) {
  47455. return _super.call(this, camera) || this;
  47456. }
  47457. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47458. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47459. return this;
  47460. };
  47461. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47462. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47463. return this;
  47464. };
  47465. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47466. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47467. return this;
  47468. };
  47469. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47470. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47471. return this;
  47472. };
  47473. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47474. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47475. return this;
  47476. };
  47477. return ArcRotateCameraInputsManager;
  47478. }(BABYLON.CameraInputsManager));
  47479. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47480. })(BABYLON || (BABYLON = {}));
  47481. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47482. var BABYLON;
  47483. (function (BABYLON) {
  47484. var ArcRotateCamera = /** @class */ (function (_super) {
  47485. __extends(ArcRotateCamera, _super);
  47486. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47487. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47488. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47489. _this.inertialAlphaOffset = 0;
  47490. _this.inertialBetaOffset = 0;
  47491. _this.inertialRadiusOffset = 0;
  47492. _this.lowerAlphaLimit = null;
  47493. _this.upperAlphaLimit = null;
  47494. _this.lowerBetaLimit = 0.01;
  47495. _this.upperBetaLimit = Math.PI;
  47496. _this.lowerRadiusLimit = null;
  47497. _this.upperRadiusLimit = null;
  47498. _this.inertialPanningX = 0;
  47499. _this.inertialPanningY = 0;
  47500. _this.pinchToPanMaxDistance = 20;
  47501. _this.panningDistanceLimit = null;
  47502. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47503. _this.panningInertia = 0.9;
  47504. //-- end properties for backward compatibility for inputs
  47505. _this.zoomOnFactor = 1;
  47506. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47507. _this.allowUpsideDown = true;
  47508. _this._viewMatrix = new BABYLON.Matrix();
  47509. // Panning
  47510. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47511. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47512. _this.checkCollisions = false;
  47513. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47514. _this._previousPosition = BABYLON.Vector3.Zero();
  47515. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47516. _this._newPosition = BABYLON.Vector3.Zero();
  47517. _this._computationVector = BABYLON.Vector3.Zero();
  47518. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47519. if (collidedMesh === void 0) { collidedMesh = null; }
  47520. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47521. newPosition.multiplyInPlace(_this._collider._radius);
  47522. }
  47523. if (!collidedMesh) {
  47524. _this._previousPosition.copyFrom(_this.position);
  47525. }
  47526. else {
  47527. _this.setPosition(newPosition);
  47528. if (_this.onCollide) {
  47529. _this.onCollide(collidedMesh);
  47530. }
  47531. }
  47532. // Recompute because of constraints
  47533. var cosa = Math.cos(_this.alpha);
  47534. var sina = Math.sin(_this.alpha);
  47535. var cosb = Math.cos(_this.beta);
  47536. var sinb = Math.sin(_this.beta);
  47537. if (sinb === 0) {
  47538. sinb = 0.0001;
  47539. }
  47540. var target = _this._getTargetPosition();
  47541. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47542. target.addToRef(_this._computationVector, _this._newPosition);
  47543. _this.position.copyFrom(_this._newPosition);
  47544. var up = _this.upVector;
  47545. if (_this.allowUpsideDown && _this.beta < 0) {
  47546. up = up.clone();
  47547. up = up.negate();
  47548. }
  47549. _this._computeViewMatrix(_this.position, target, up);
  47550. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47551. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47552. _this._collisionTriggered = false;
  47553. };
  47554. _this._target = BABYLON.Vector3.Zero();
  47555. if (target) {
  47556. _this.setTarget(target);
  47557. }
  47558. _this.alpha = alpha;
  47559. _this.beta = beta;
  47560. _this.radius = radius;
  47561. _this.getViewMatrix();
  47562. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47563. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47564. return _this;
  47565. }
  47566. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47567. get: function () {
  47568. return this._target;
  47569. },
  47570. set: function (value) {
  47571. this.setTarget(value);
  47572. },
  47573. enumerable: true,
  47574. configurable: true
  47575. });
  47576. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47577. //-- begin properties for backward compatibility for inputs
  47578. get: function () {
  47579. var pointers = this.inputs.attached["pointers"];
  47580. if (pointers)
  47581. return pointers.angularSensibilityX;
  47582. return 0;
  47583. },
  47584. set: function (value) {
  47585. var pointers = this.inputs.attached["pointers"];
  47586. if (pointers) {
  47587. pointers.angularSensibilityX = value;
  47588. }
  47589. },
  47590. enumerable: true,
  47591. configurable: true
  47592. });
  47593. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47594. get: function () {
  47595. var pointers = this.inputs.attached["pointers"];
  47596. if (pointers)
  47597. return pointers.angularSensibilityY;
  47598. return 0;
  47599. },
  47600. set: function (value) {
  47601. var pointers = this.inputs.attached["pointers"];
  47602. if (pointers) {
  47603. pointers.angularSensibilityY = value;
  47604. }
  47605. },
  47606. enumerable: true,
  47607. configurable: true
  47608. });
  47609. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47610. get: function () {
  47611. var pointers = this.inputs.attached["pointers"];
  47612. if (pointers)
  47613. return pointers.pinchPrecision;
  47614. return 0;
  47615. },
  47616. set: function (value) {
  47617. var pointers = this.inputs.attached["pointers"];
  47618. if (pointers) {
  47619. pointers.pinchPrecision = value;
  47620. }
  47621. },
  47622. enumerable: true,
  47623. configurable: true
  47624. });
  47625. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47626. get: function () {
  47627. var pointers = this.inputs.attached["pointers"];
  47628. if (pointers)
  47629. return pointers.pinchDeltaPercentage;
  47630. return 0;
  47631. },
  47632. set: function (value) {
  47633. var pointers = this.inputs.attached["pointers"];
  47634. if (pointers) {
  47635. pointers.pinchDeltaPercentage = value;
  47636. }
  47637. },
  47638. enumerable: true,
  47639. configurable: true
  47640. });
  47641. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47642. get: function () {
  47643. var pointers = this.inputs.attached["pointers"];
  47644. if (pointers)
  47645. return pointers.panningSensibility;
  47646. return 0;
  47647. },
  47648. set: function (value) {
  47649. var pointers = this.inputs.attached["pointers"];
  47650. if (pointers) {
  47651. pointers.panningSensibility = value;
  47652. }
  47653. },
  47654. enumerable: true,
  47655. configurable: true
  47656. });
  47657. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47658. get: function () {
  47659. var keyboard = this.inputs.attached["keyboard"];
  47660. if (keyboard)
  47661. return keyboard.keysUp;
  47662. return [];
  47663. },
  47664. set: function (value) {
  47665. var keyboard = this.inputs.attached["keyboard"];
  47666. if (keyboard)
  47667. keyboard.keysUp = value;
  47668. },
  47669. enumerable: true,
  47670. configurable: true
  47671. });
  47672. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47673. get: function () {
  47674. var keyboard = this.inputs.attached["keyboard"];
  47675. if (keyboard)
  47676. return keyboard.keysDown;
  47677. return [];
  47678. },
  47679. set: function (value) {
  47680. var keyboard = this.inputs.attached["keyboard"];
  47681. if (keyboard)
  47682. keyboard.keysDown = value;
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47688. get: function () {
  47689. var keyboard = this.inputs.attached["keyboard"];
  47690. if (keyboard)
  47691. return keyboard.keysLeft;
  47692. return [];
  47693. },
  47694. set: function (value) {
  47695. var keyboard = this.inputs.attached["keyboard"];
  47696. if (keyboard)
  47697. keyboard.keysLeft = value;
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47703. get: function () {
  47704. var keyboard = this.inputs.attached["keyboard"];
  47705. if (keyboard)
  47706. return keyboard.keysRight;
  47707. return [];
  47708. },
  47709. set: function (value) {
  47710. var keyboard = this.inputs.attached["keyboard"];
  47711. if (keyboard)
  47712. keyboard.keysRight = value;
  47713. },
  47714. enumerable: true,
  47715. configurable: true
  47716. });
  47717. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47718. get: function () {
  47719. var mousewheel = this.inputs.attached["mousewheel"];
  47720. if (mousewheel)
  47721. return mousewheel.wheelPrecision;
  47722. return 0;
  47723. },
  47724. set: function (value) {
  47725. var mousewheel = this.inputs.attached["mousewheel"];
  47726. if (mousewheel)
  47727. mousewheel.wheelPrecision = value;
  47728. },
  47729. enumerable: true,
  47730. configurable: true
  47731. });
  47732. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47733. get: function () {
  47734. var mousewheel = this.inputs.attached["mousewheel"];
  47735. if (mousewheel)
  47736. return mousewheel.wheelDeltaPercentage;
  47737. return 0;
  47738. },
  47739. set: function (value) {
  47740. var mousewheel = this.inputs.attached["mousewheel"];
  47741. if (mousewheel)
  47742. mousewheel.wheelDeltaPercentage = value;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47748. get: function () {
  47749. return this._bouncingBehavior;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47755. get: function () {
  47756. return this._bouncingBehavior != null;
  47757. },
  47758. set: function (value) {
  47759. if (value === this.useBouncingBehavior) {
  47760. return;
  47761. }
  47762. if (value) {
  47763. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47764. this.addBehavior(this._bouncingBehavior);
  47765. }
  47766. else if (this._bouncingBehavior) {
  47767. this.removeBehavior(this._bouncingBehavior);
  47768. this._bouncingBehavior = null;
  47769. }
  47770. },
  47771. enumerable: true,
  47772. configurable: true
  47773. });
  47774. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47775. get: function () {
  47776. return this._framingBehavior;
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47782. get: function () {
  47783. return this._framingBehavior != null;
  47784. },
  47785. set: function (value) {
  47786. if (value === this.useFramingBehavior) {
  47787. return;
  47788. }
  47789. if (value) {
  47790. this._framingBehavior = new BABYLON.FramingBehavior();
  47791. this.addBehavior(this._framingBehavior);
  47792. }
  47793. else if (this._framingBehavior) {
  47794. this.removeBehavior(this._framingBehavior);
  47795. this._framingBehavior = null;
  47796. }
  47797. },
  47798. enumerable: true,
  47799. configurable: true
  47800. });
  47801. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47802. get: function () {
  47803. return this._autoRotationBehavior;
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47809. get: function () {
  47810. return this._autoRotationBehavior != null;
  47811. },
  47812. set: function (value) {
  47813. if (value === this.useAutoRotationBehavior) {
  47814. return;
  47815. }
  47816. if (value) {
  47817. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47818. this.addBehavior(this._autoRotationBehavior);
  47819. }
  47820. else if (this._autoRotationBehavior) {
  47821. this.removeBehavior(this._autoRotationBehavior);
  47822. this._autoRotationBehavior = null;
  47823. }
  47824. },
  47825. enumerable: true,
  47826. configurable: true
  47827. });
  47828. // Cache
  47829. ArcRotateCamera.prototype._initCache = function () {
  47830. _super.prototype._initCache.call(this);
  47831. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47832. this._cache.alpha = undefined;
  47833. this._cache.beta = undefined;
  47834. this._cache.radius = undefined;
  47835. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47836. };
  47837. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47838. if (!ignoreParentClass) {
  47839. _super.prototype._updateCache.call(this);
  47840. }
  47841. this._cache._target.copyFrom(this._getTargetPosition());
  47842. this._cache.alpha = this.alpha;
  47843. this._cache.beta = this.beta;
  47844. this._cache.radius = this.radius;
  47845. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47846. };
  47847. ArcRotateCamera.prototype._getTargetPosition = function () {
  47848. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47849. var pos = this._targetHost.getAbsolutePosition();
  47850. if (this._targetBoundingCenter) {
  47851. pos.addToRef(this._targetBoundingCenter, this._target);
  47852. }
  47853. else {
  47854. this._target.copyFrom(pos);
  47855. }
  47856. }
  47857. var lockedTargetPosition = this._getLockedTargetPosition();
  47858. if (lockedTargetPosition) {
  47859. return lockedTargetPosition;
  47860. }
  47861. return this._target;
  47862. };
  47863. ArcRotateCamera.prototype.storeState = function () {
  47864. this._storedAlpha = this.alpha;
  47865. this._storedBeta = this.beta;
  47866. this._storedRadius = this.radius;
  47867. this._storedTarget = this._getTargetPosition().clone();
  47868. return _super.prototype.storeState.call(this);
  47869. };
  47870. /**
  47871. * Restored camera state. You must call storeState() first
  47872. */
  47873. ArcRotateCamera.prototype._restoreStateValues = function () {
  47874. if (!_super.prototype._restoreStateValues.call(this)) {
  47875. return false;
  47876. }
  47877. this.alpha = this._storedAlpha;
  47878. this.beta = this._storedBeta;
  47879. this.radius = this._storedRadius;
  47880. this.setTarget(this._storedTarget.clone());
  47881. this.inertialAlphaOffset = 0;
  47882. this.inertialBetaOffset = 0;
  47883. this.inertialRadiusOffset = 0;
  47884. this.inertialPanningX = 0;
  47885. this.inertialPanningY = 0;
  47886. return true;
  47887. };
  47888. // Synchronized
  47889. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47890. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47891. return false;
  47892. return this._cache._target.equals(this._getTargetPosition())
  47893. && this._cache.alpha === this.alpha
  47894. && this._cache.beta === this.beta
  47895. && this._cache.radius === this.radius
  47896. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47897. };
  47898. // Methods
  47899. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47900. var _this = this;
  47901. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47902. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47903. this._useCtrlForPanning = useCtrlForPanning;
  47904. this._panningMouseButton = panningMouseButton;
  47905. this.inputs.attachElement(element, noPreventDefault);
  47906. this._reset = function () {
  47907. _this.inertialAlphaOffset = 0;
  47908. _this.inertialBetaOffset = 0;
  47909. _this.inertialRadiusOffset = 0;
  47910. _this.inertialPanningX = 0;
  47911. _this.inertialPanningY = 0;
  47912. };
  47913. };
  47914. ArcRotateCamera.prototype.detachControl = function (element) {
  47915. this.inputs.detachElement(element);
  47916. if (this._reset) {
  47917. this._reset();
  47918. }
  47919. };
  47920. ArcRotateCamera.prototype._checkInputs = function () {
  47921. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47922. if (this._collisionTriggered) {
  47923. return;
  47924. }
  47925. this.inputs.checkInputs();
  47926. // Inertia
  47927. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47928. var inertialAlphaOffset = this.inertialAlphaOffset;
  47929. if (this.beta <= 0)
  47930. inertialAlphaOffset *= -1;
  47931. if (this.getScene().useRightHandedSystem)
  47932. inertialAlphaOffset *= -1;
  47933. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47934. inertialAlphaOffset *= -1;
  47935. this.alpha += inertialAlphaOffset;
  47936. this.beta += this.inertialBetaOffset;
  47937. this.radius -= this.inertialRadiusOffset;
  47938. this.inertialAlphaOffset *= this.inertia;
  47939. this.inertialBetaOffset *= this.inertia;
  47940. this.inertialRadiusOffset *= this.inertia;
  47941. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47942. this.inertialAlphaOffset = 0;
  47943. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47944. this.inertialBetaOffset = 0;
  47945. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47946. this.inertialRadiusOffset = 0;
  47947. }
  47948. // Panning inertia
  47949. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47950. if (!this._localDirection) {
  47951. this._localDirection = BABYLON.Vector3.Zero();
  47952. this._transformedDirection = BABYLON.Vector3.Zero();
  47953. }
  47954. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47955. this._localDirection.multiplyInPlace(this.panningAxis);
  47956. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47957. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47958. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47959. if (!this.panningAxis.y) {
  47960. this._transformedDirection.y = 0;
  47961. }
  47962. if (!this._targetHost) {
  47963. if (this.panningDistanceLimit) {
  47964. this._transformedDirection.addInPlace(this._target);
  47965. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47966. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47967. this._target.copyFrom(this._transformedDirection);
  47968. }
  47969. }
  47970. else {
  47971. this._target.addInPlace(this._transformedDirection);
  47972. }
  47973. }
  47974. this.inertialPanningX *= this.panningInertia;
  47975. this.inertialPanningY *= this.panningInertia;
  47976. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47977. this.inertialPanningX = 0;
  47978. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47979. this.inertialPanningY = 0;
  47980. }
  47981. // Limits
  47982. this._checkLimits();
  47983. _super.prototype._checkInputs.call(this);
  47984. };
  47985. ArcRotateCamera.prototype._checkLimits = function () {
  47986. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47987. if (this.allowUpsideDown && this.beta > Math.PI) {
  47988. this.beta = this.beta - (2 * Math.PI);
  47989. }
  47990. }
  47991. else {
  47992. if (this.beta < this.lowerBetaLimit) {
  47993. this.beta = this.lowerBetaLimit;
  47994. }
  47995. }
  47996. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47997. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47998. this.beta = this.beta + (2 * Math.PI);
  47999. }
  48000. }
  48001. else {
  48002. if (this.beta > this.upperBetaLimit) {
  48003. this.beta = this.upperBetaLimit;
  48004. }
  48005. }
  48006. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48007. this.alpha = this.lowerAlphaLimit;
  48008. }
  48009. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48010. this.alpha = this.upperAlphaLimit;
  48011. }
  48012. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48013. this.radius = this.lowerRadiusLimit;
  48014. }
  48015. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48016. this.radius = this.upperRadiusLimit;
  48017. }
  48018. };
  48019. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48020. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48021. this.radius = this._computationVector.length();
  48022. if (this.radius === 0) {
  48023. this.radius = 0.0001; // Just to avoid division by zero
  48024. }
  48025. // Alpha
  48026. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48027. if (this._computationVector.z < 0) {
  48028. this.alpha = 2 * Math.PI - this.alpha;
  48029. }
  48030. // Beta
  48031. this.beta = Math.acos(this._computationVector.y / this.radius);
  48032. this._checkLimits();
  48033. };
  48034. ArcRotateCamera.prototype.setPosition = function (position) {
  48035. if (this.position.equals(position)) {
  48036. return;
  48037. }
  48038. this.position.copyFrom(position);
  48039. this.rebuildAnglesAndRadius();
  48040. };
  48041. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48042. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48043. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48044. if (target.getBoundingInfo) {
  48045. if (toBoundingCenter) {
  48046. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48047. }
  48048. else {
  48049. this._targetBoundingCenter = null;
  48050. }
  48051. this._targetHost = target;
  48052. this._target = this._getTargetPosition();
  48053. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48054. }
  48055. else {
  48056. var newTarget = target;
  48057. var currentTarget = this._getTargetPosition();
  48058. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48059. return;
  48060. }
  48061. this._targetHost = null;
  48062. this._target = newTarget;
  48063. this._targetBoundingCenter = null;
  48064. this.onMeshTargetChangedObservable.notifyObservers(null);
  48065. }
  48066. this.rebuildAnglesAndRadius();
  48067. };
  48068. ArcRotateCamera.prototype._getViewMatrix = function () {
  48069. // Compute
  48070. var cosa = Math.cos(this.alpha);
  48071. var sina = Math.sin(this.alpha);
  48072. var cosb = Math.cos(this.beta);
  48073. var sinb = Math.sin(this.beta);
  48074. if (sinb === 0) {
  48075. sinb = 0.0001;
  48076. }
  48077. var target = this._getTargetPosition();
  48078. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48079. target.addToRef(this._computationVector, this._newPosition);
  48080. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48081. if (!this._collider) {
  48082. this._collider = new BABYLON.Collider();
  48083. }
  48084. this._collider._radius = this.collisionRadius;
  48085. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48086. this._collisionTriggered = true;
  48087. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48088. }
  48089. else {
  48090. this.position.copyFrom(this._newPosition);
  48091. var up = this.upVector;
  48092. if (this.allowUpsideDown && sinb < 0) {
  48093. up = up.clone();
  48094. up = up.negate();
  48095. }
  48096. this._computeViewMatrix(this.position, target, up);
  48097. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48098. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48099. }
  48100. this._currentTarget = target;
  48101. return this._viewMatrix;
  48102. };
  48103. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48104. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48105. meshes = meshes || this.getScene().meshes;
  48106. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48107. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48108. this.radius = distance * this.zoomOnFactor;
  48109. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48110. };
  48111. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48112. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48113. var meshesOrMinMaxVector;
  48114. var distance;
  48115. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48116. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48117. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48118. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48119. }
  48120. else { //minMaxVector and distance
  48121. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48122. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48123. distance = minMaxVectorAndDistance.distance;
  48124. }
  48125. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48126. if (!doNotUpdateMaxZ) {
  48127. this.maxZ = distance * 2;
  48128. }
  48129. };
  48130. /**
  48131. * @override
  48132. * Override Camera.createRigCamera
  48133. */
  48134. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48135. var alphaShift = 0;
  48136. switch (this.cameraRigMode) {
  48137. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48138. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48140. case BABYLON.Camera.RIG_MODE_VR:
  48141. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48142. break;
  48143. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48144. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48145. break;
  48146. }
  48147. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48148. rigCam._cameraRigParams = {};
  48149. return rigCam;
  48150. };
  48151. /**
  48152. * @override
  48153. * Override Camera._updateRigCameras
  48154. */
  48155. ArcRotateCamera.prototype._updateRigCameras = function () {
  48156. var camLeft = this._rigCameras[0];
  48157. var camRight = this._rigCameras[1];
  48158. camLeft.beta = camRight.beta = this.beta;
  48159. camLeft.radius = camRight.radius = this.radius;
  48160. switch (this.cameraRigMode) {
  48161. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48162. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48164. case BABYLON.Camera.RIG_MODE_VR:
  48165. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48166. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48167. break;
  48168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48169. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48170. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48171. break;
  48172. }
  48173. _super.prototype._updateRigCameras.call(this);
  48174. };
  48175. ArcRotateCamera.prototype.dispose = function () {
  48176. this.inputs.clear();
  48177. _super.prototype.dispose.call(this);
  48178. };
  48179. ArcRotateCamera.prototype.getClassName = function () {
  48180. return "ArcRotateCamera";
  48181. };
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCamera.prototype, "alpha", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCamera.prototype, "beta", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCamera.prototype, "radius", void 0);
  48191. __decorate([
  48192. BABYLON.serializeAsVector3("target")
  48193. ], ArcRotateCamera.prototype, "_target", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48212. __decorate([
  48213. BABYLON.serialize()
  48214. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48215. __decorate([
  48216. BABYLON.serialize()
  48217. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48218. __decorate([
  48219. BABYLON.serialize()
  48220. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48221. __decorate([
  48222. BABYLON.serialize()
  48223. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48224. __decorate([
  48225. BABYLON.serialize()
  48226. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48227. __decorate([
  48228. BABYLON.serialize()
  48229. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48230. __decorate([
  48231. BABYLON.serialize()
  48232. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48233. __decorate([
  48234. BABYLON.serializeAsVector3()
  48235. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48236. __decorate([
  48237. BABYLON.serialize()
  48238. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48239. __decorate([
  48240. BABYLON.serialize()
  48241. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48242. __decorate([
  48243. BABYLON.serialize()
  48244. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48245. return ArcRotateCamera;
  48246. }(BABYLON.TargetCamera));
  48247. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48248. })(BABYLON || (BABYLON = {}));
  48249. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48250. var BABYLON;
  48251. (function (BABYLON) {
  48252. /**
  48253. * The HemisphericLight simulates the ambient environment light,
  48254. * so the passed direction is the light reflection direction, not the incoming direction.
  48255. */
  48256. var HemisphericLight = /** @class */ (function (_super) {
  48257. __extends(HemisphericLight, _super);
  48258. /**
  48259. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48260. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48261. * The HemisphericLight can't cast shadows.
  48262. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48263. * @param name The friendly name of the light
  48264. * @param direction The direction of the light reflection
  48265. * @param scene The scene the light belongs to
  48266. */
  48267. function HemisphericLight(name, direction, scene) {
  48268. var _this = _super.call(this, name, scene) || this;
  48269. /**
  48270. * The groundColor is the light in the opposite direction to the one specified during creation.
  48271. * 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.
  48272. */
  48273. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48274. _this.direction = direction || BABYLON.Vector3.Up();
  48275. return _this;
  48276. }
  48277. HemisphericLight.prototype._buildUniformLayout = function () {
  48278. this._uniformBuffer.addUniform("vLightData", 4);
  48279. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48280. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48281. this._uniformBuffer.addUniform("vLightGround", 3);
  48282. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48283. this._uniformBuffer.addUniform("depthValues", 2);
  48284. this._uniformBuffer.create();
  48285. };
  48286. /**
  48287. * Returns the string "HemisphericLight".
  48288. * @return The class name
  48289. */
  48290. HemisphericLight.prototype.getClassName = function () {
  48291. return "HemisphericLight";
  48292. };
  48293. /**
  48294. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48295. * Returns the updated direction.
  48296. * @param target The target the direction should point to
  48297. * @return The computed direction
  48298. */
  48299. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48300. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48301. return this.direction;
  48302. };
  48303. /**
  48304. * Returns the shadow generator associated to the light.
  48305. * @returns Always null for hemispheric lights because it does not support shadows.
  48306. */
  48307. HemisphericLight.prototype.getShadowGenerator = function () {
  48308. return null;
  48309. };
  48310. /**
  48311. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48312. * @param effect The effect to update
  48313. * @param lightIndex The index of the light in the effect to update
  48314. * @returns The hemispheric light
  48315. */
  48316. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48317. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48318. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48319. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48320. return this;
  48321. };
  48322. /**
  48323. * @hidden internal use only.
  48324. */
  48325. HemisphericLight.prototype._getWorldMatrix = function () {
  48326. if (!this._worldMatrix) {
  48327. this._worldMatrix = BABYLON.Matrix.Identity();
  48328. }
  48329. return this._worldMatrix;
  48330. };
  48331. /**
  48332. * Returns the integer 3.
  48333. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48334. */
  48335. HemisphericLight.prototype.getTypeID = function () {
  48336. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48337. };
  48338. __decorate([
  48339. BABYLON.serializeAsColor3()
  48340. ], HemisphericLight.prototype, "groundColor", void 0);
  48341. __decorate([
  48342. BABYLON.serializeAsVector3()
  48343. ], HemisphericLight.prototype, "direction", void 0);
  48344. return HemisphericLight;
  48345. }(BABYLON.Light));
  48346. BABYLON.HemisphericLight = HemisphericLight;
  48347. })(BABYLON || (BABYLON = {}));
  48348. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48349. var BABYLON;
  48350. (function (BABYLON) {
  48351. /**
  48352. * Base implementation IShadowLight
  48353. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48354. */
  48355. var ShadowLight = /** @class */ (function (_super) {
  48356. __extends(ShadowLight, _super);
  48357. function ShadowLight() {
  48358. var _this = _super !== null && _super.apply(this, arguments) || this;
  48359. _this._needProjectionMatrixCompute = true;
  48360. return _this;
  48361. }
  48362. ShadowLight.prototype._setPosition = function (value) {
  48363. this._position = value;
  48364. };
  48365. Object.defineProperty(ShadowLight.prototype, "position", {
  48366. /**
  48367. * Sets the position the shadow will be casted from. Also use as the light position for both
  48368. * point and spot lights.
  48369. */
  48370. get: function () {
  48371. return this._position;
  48372. },
  48373. /**
  48374. * Sets the position the shadow will be casted from. Also use as the light position for both
  48375. * point and spot lights.
  48376. */
  48377. set: function (value) {
  48378. this._setPosition(value);
  48379. },
  48380. enumerable: true,
  48381. configurable: true
  48382. });
  48383. ShadowLight.prototype._setDirection = function (value) {
  48384. this._direction = value;
  48385. };
  48386. Object.defineProperty(ShadowLight.prototype, "direction", {
  48387. /**
  48388. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48389. * Also use as the light direction on spot and directional lights.
  48390. */
  48391. get: function () {
  48392. return this._direction;
  48393. },
  48394. /**
  48395. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48396. * Also use as the light direction on spot and directional lights.
  48397. */
  48398. set: function (value) {
  48399. this._setDirection(value);
  48400. },
  48401. enumerable: true,
  48402. configurable: true
  48403. });
  48404. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48405. /**
  48406. * Gets the shadow projection clipping minimum z value.
  48407. */
  48408. get: function () {
  48409. return this._shadowMinZ;
  48410. },
  48411. /**
  48412. * Sets the shadow projection clipping minimum z value.
  48413. */
  48414. set: function (value) {
  48415. this._shadowMinZ = value;
  48416. this.forceProjectionMatrixCompute();
  48417. },
  48418. enumerable: true,
  48419. configurable: true
  48420. });
  48421. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48422. /**
  48423. * Sets the shadow projection clipping maximum z value.
  48424. */
  48425. get: function () {
  48426. return this._shadowMaxZ;
  48427. },
  48428. /**
  48429. * Gets the shadow projection clipping maximum z value.
  48430. */
  48431. set: function (value) {
  48432. this._shadowMaxZ = value;
  48433. this.forceProjectionMatrixCompute();
  48434. },
  48435. enumerable: true,
  48436. configurable: true
  48437. });
  48438. /**
  48439. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48440. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48441. */
  48442. ShadowLight.prototype.computeTransformedInformation = function () {
  48443. if (this.parent && this.parent.getWorldMatrix) {
  48444. if (!this.transformedPosition) {
  48445. this.transformedPosition = BABYLON.Vector3.Zero();
  48446. }
  48447. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48448. // In case the direction is present.
  48449. if (this.direction) {
  48450. if (!this.transformedDirection) {
  48451. this.transformedDirection = BABYLON.Vector3.Zero();
  48452. }
  48453. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48454. }
  48455. return true;
  48456. }
  48457. return false;
  48458. };
  48459. /**
  48460. * Return the depth scale used for the shadow map.
  48461. * @returns the depth scale.
  48462. */
  48463. ShadowLight.prototype.getDepthScale = function () {
  48464. return 50.0;
  48465. };
  48466. /**
  48467. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48468. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48469. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48470. */
  48471. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48472. return this.transformedDirection ? this.transformedDirection : this.direction;
  48473. };
  48474. /**
  48475. * Returns the ShadowLight absolute position in the World.
  48476. * @returns the position vector in world space
  48477. */
  48478. ShadowLight.prototype.getAbsolutePosition = function () {
  48479. return this.transformedPosition ? this.transformedPosition : this.position;
  48480. };
  48481. /**
  48482. * Sets the ShadowLight direction toward the passed target.
  48483. * @param target The point tot target in local space
  48484. * @returns the updated ShadowLight direction
  48485. */
  48486. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48487. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48488. return this.direction;
  48489. };
  48490. /**
  48491. * Returns the light rotation in euler definition.
  48492. * @returns the x y z rotation in local space.
  48493. */
  48494. ShadowLight.prototype.getRotation = function () {
  48495. this.direction.normalize();
  48496. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48497. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48498. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48499. };
  48500. /**
  48501. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48502. * @returns true if a cube texture needs to be use
  48503. */
  48504. ShadowLight.prototype.needCube = function () {
  48505. return false;
  48506. };
  48507. /**
  48508. * Detects if the projection matrix requires to be recomputed this frame.
  48509. * @returns true if it requires to be recomputed otherwise, false.
  48510. */
  48511. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48512. return this._needProjectionMatrixCompute;
  48513. };
  48514. /**
  48515. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48516. */
  48517. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48518. this._needProjectionMatrixCompute = true;
  48519. };
  48520. /**
  48521. * Get the world matrix of the sahdow lights.
  48522. * @hidden Internal Use Only
  48523. */
  48524. ShadowLight.prototype._getWorldMatrix = function () {
  48525. if (!this._worldMatrix) {
  48526. this._worldMatrix = BABYLON.Matrix.Identity();
  48527. }
  48528. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48529. return this._worldMatrix;
  48530. };
  48531. /**
  48532. * Gets the minZ used for shadow according to both the scene and the light.
  48533. * @param activeCamera The camera we are returning the min for
  48534. * @returns the depth min z
  48535. */
  48536. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48537. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48538. };
  48539. /**
  48540. * Gets the maxZ used for shadow according to both the scene and the light.
  48541. * @param activeCamera The camera we are returning the max for
  48542. * @returns the depth max z
  48543. */
  48544. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48545. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48546. };
  48547. /**
  48548. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48549. * @param matrix The materix to updated with the projection information
  48550. * @param viewMatrix The transform matrix of the light
  48551. * @param renderList The list of mesh to render in the map
  48552. * @returns The current light
  48553. */
  48554. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48555. if (this.customProjectionMatrixBuilder) {
  48556. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48557. }
  48558. else {
  48559. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48560. }
  48561. return this;
  48562. };
  48563. __decorate([
  48564. BABYLON.serializeAsVector3()
  48565. ], ShadowLight.prototype, "position", null);
  48566. __decorate([
  48567. BABYLON.serializeAsVector3()
  48568. ], ShadowLight.prototype, "direction", null);
  48569. __decorate([
  48570. BABYLON.serialize()
  48571. ], ShadowLight.prototype, "shadowMinZ", null);
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], ShadowLight.prototype, "shadowMaxZ", null);
  48575. return ShadowLight;
  48576. }(BABYLON.Light));
  48577. BABYLON.ShadowLight = ShadowLight;
  48578. })(BABYLON || (BABYLON = {}));
  48579. //# sourceMappingURL=babylon.shadowLight.js.map
  48580. var BABYLON;
  48581. (function (BABYLON) {
  48582. /**
  48583. * A point light is a light defined by an unique point in world space.
  48584. * The light is emitted in every direction from this point.
  48585. * A good example of a point light is a standard light bulb.
  48586. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48587. */
  48588. var PointLight = /** @class */ (function (_super) {
  48589. __extends(PointLight, _super);
  48590. /**
  48591. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48592. * A PointLight emits the light in every direction.
  48593. * It can cast shadows.
  48594. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48595. * ```javascript
  48596. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48597. * ```
  48598. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48599. * @param name The light friendly name
  48600. * @param position The position of the point light in the scene
  48601. * @param scene The scene the lights belongs to
  48602. */
  48603. function PointLight(name, position, scene) {
  48604. var _this = _super.call(this, name, scene) || this;
  48605. _this._shadowAngle = Math.PI / 2;
  48606. _this.position = position;
  48607. return _this;
  48608. }
  48609. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48610. /**
  48611. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48612. * This specifies what angle the shadow will use to be created.
  48613. *
  48614. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48615. */
  48616. get: function () {
  48617. return this._shadowAngle;
  48618. },
  48619. /**
  48620. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48621. * This specifies what angle the shadow will use to be created.
  48622. *
  48623. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48624. */
  48625. set: function (value) {
  48626. this._shadowAngle = value;
  48627. this.forceProjectionMatrixCompute();
  48628. },
  48629. enumerable: true,
  48630. configurable: true
  48631. });
  48632. Object.defineProperty(PointLight.prototype, "direction", {
  48633. /**
  48634. * Gets the direction if it has been set.
  48635. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48636. */
  48637. get: function () {
  48638. return this._direction;
  48639. },
  48640. /**
  48641. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48642. */
  48643. set: function (value) {
  48644. var previousNeedCube = this.needCube();
  48645. this._direction = value;
  48646. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48647. this._shadowGenerator.recreateShadowMap();
  48648. }
  48649. },
  48650. enumerable: true,
  48651. configurable: true
  48652. });
  48653. /**
  48654. * Returns the string "PointLight"
  48655. * @returns the class name
  48656. */
  48657. PointLight.prototype.getClassName = function () {
  48658. return "PointLight";
  48659. };
  48660. /**
  48661. * Returns the integer 0.
  48662. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48663. */
  48664. PointLight.prototype.getTypeID = function () {
  48665. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48666. };
  48667. /**
  48668. * Specifies wether or not the shadowmap should be a cube texture.
  48669. * @returns true if the shadowmap needs to be a cube texture.
  48670. */
  48671. PointLight.prototype.needCube = function () {
  48672. return !this.direction;
  48673. };
  48674. /**
  48675. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48676. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48677. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48678. */
  48679. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48680. if (this.direction) {
  48681. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48682. }
  48683. else {
  48684. switch (faceIndex) {
  48685. case 0:
  48686. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48687. case 1:
  48688. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48689. case 2:
  48690. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48691. case 3:
  48692. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48693. case 4:
  48694. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48695. case 5:
  48696. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48697. }
  48698. }
  48699. return BABYLON.Vector3.Zero();
  48700. };
  48701. /**
  48702. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48703. * - fov = PI / 2
  48704. * - aspect ratio : 1.0
  48705. * - z-near and far equal to the active camera minZ and maxZ.
  48706. * Returns the PointLight.
  48707. */
  48708. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48709. var activeCamera = this.getScene().activeCamera;
  48710. if (!activeCamera) {
  48711. return;
  48712. }
  48713. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48714. };
  48715. PointLight.prototype._buildUniformLayout = function () {
  48716. this._uniformBuffer.addUniform("vLightData", 4);
  48717. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48718. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48719. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48720. this._uniformBuffer.addUniform("depthValues", 2);
  48721. this._uniformBuffer.create();
  48722. };
  48723. /**
  48724. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48725. * @param effect The effect to update
  48726. * @param lightIndex The index of the light in the effect to update
  48727. * @returns The point light
  48728. */
  48729. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48730. if (this.computeTransformedInformation()) {
  48731. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48732. return this;
  48733. }
  48734. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48735. return this;
  48736. };
  48737. __decorate([
  48738. BABYLON.serialize()
  48739. ], PointLight.prototype, "shadowAngle", null);
  48740. return PointLight;
  48741. }(BABYLON.ShadowLight));
  48742. BABYLON.PointLight = PointLight;
  48743. })(BABYLON || (BABYLON = {}));
  48744. //# sourceMappingURL=babylon.pointLight.js.map
  48745. var BABYLON;
  48746. (function (BABYLON) {
  48747. /**
  48748. * A directional light is defined by a direction (what a surprise!).
  48749. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48750. * 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.
  48751. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48752. */
  48753. var DirectionalLight = /** @class */ (function (_super) {
  48754. __extends(DirectionalLight, _super);
  48755. /**
  48756. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48757. * The directional light is emitted from everywhere in the given direction.
  48758. * It can cast shawdows.
  48759. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48760. * @param name The friendly name of the light
  48761. * @param direction The direction of the light
  48762. * @param scene The scene the light belongs to
  48763. */
  48764. function DirectionalLight(name, direction, scene) {
  48765. var _this = _super.call(this, name, scene) || this;
  48766. _this._shadowFrustumSize = 0;
  48767. _this._shadowOrthoScale = 0.1;
  48768. /**
  48769. * Automatically compute the projection matrix to best fit (including all the casters)
  48770. * on each frame.
  48771. */
  48772. _this.autoUpdateExtends = true;
  48773. // Cache
  48774. _this._orthoLeft = Number.MAX_VALUE;
  48775. _this._orthoRight = Number.MIN_VALUE;
  48776. _this._orthoTop = Number.MIN_VALUE;
  48777. _this._orthoBottom = Number.MAX_VALUE;
  48778. _this.position = direction.scale(-1.0);
  48779. _this.direction = direction;
  48780. return _this;
  48781. }
  48782. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48783. /**
  48784. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48785. */
  48786. get: function () {
  48787. return this._shadowFrustumSize;
  48788. },
  48789. /**
  48790. * Specifies a fix frustum size for the shadow generation.
  48791. */
  48792. set: function (value) {
  48793. this._shadowFrustumSize = value;
  48794. this.forceProjectionMatrixCompute();
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48800. /**
  48801. * Gets the shadow projection scale against the optimal computed one.
  48802. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48803. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48804. */
  48805. get: function () {
  48806. return this._shadowOrthoScale;
  48807. },
  48808. /**
  48809. * Sets the shadow projection scale against the optimal computed one.
  48810. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48811. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48812. */
  48813. set: function (value) {
  48814. this._shadowOrthoScale = value;
  48815. this.forceProjectionMatrixCompute();
  48816. },
  48817. enumerable: true,
  48818. configurable: true
  48819. });
  48820. /**
  48821. * Returns the string "DirectionalLight".
  48822. * @return The class name
  48823. */
  48824. DirectionalLight.prototype.getClassName = function () {
  48825. return "DirectionalLight";
  48826. };
  48827. /**
  48828. * Returns the integer 1.
  48829. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48830. */
  48831. DirectionalLight.prototype.getTypeID = function () {
  48832. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48833. };
  48834. /**
  48835. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48836. * Returns the DirectionalLight Shadow projection matrix.
  48837. */
  48838. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48839. if (this.shadowFrustumSize > 0) {
  48840. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48841. }
  48842. else {
  48843. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48844. }
  48845. };
  48846. /**
  48847. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48848. * Returns the DirectionalLight Shadow projection matrix.
  48849. */
  48850. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48851. var activeCamera = this.getScene().activeCamera;
  48852. if (!activeCamera) {
  48853. return;
  48854. }
  48855. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48856. };
  48857. /**
  48858. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48859. * Returns the DirectionalLight Shadow projection matrix.
  48860. */
  48861. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48862. var activeCamera = this.getScene().activeCamera;
  48863. if (!activeCamera) {
  48864. return;
  48865. }
  48866. // Check extends
  48867. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48868. var tempVector3 = BABYLON.Vector3.Zero();
  48869. this._orthoLeft = Number.MAX_VALUE;
  48870. this._orthoRight = Number.MIN_VALUE;
  48871. this._orthoTop = Number.MIN_VALUE;
  48872. this._orthoBottom = Number.MAX_VALUE;
  48873. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48874. var mesh = renderList[meshIndex];
  48875. if (!mesh) {
  48876. continue;
  48877. }
  48878. var boundingInfo = mesh.getBoundingInfo();
  48879. var boundingBox = boundingInfo.boundingBox;
  48880. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48881. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48882. if (tempVector3.x < this._orthoLeft)
  48883. this._orthoLeft = tempVector3.x;
  48884. if (tempVector3.y < this._orthoBottom)
  48885. this._orthoBottom = tempVector3.y;
  48886. if (tempVector3.x > this._orthoRight)
  48887. this._orthoRight = tempVector3.x;
  48888. if (tempVector3.y > this._orthoTop)
  48889. this._orthoTop = tempVector3.y;
  48890. }
  48891. }
  48892. }
  48893. var xOffset = this._orthoRight - this._orthoLeft;
  48894. var yOffset = this._orthoTop - this._orthoBottom;
  48895. 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);
  48896. };
  48897. DirectionalLight.prototype._buildUniformLayout = function () {
  48898. this._uniformBuffer.addUniform("vLightData", 4);
  48899. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48900. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48901. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48902. this._uniformBuffer.addUniform("depthValues", 2);
  48903. this._uniformBuffer.create();
  48904. };
  48905. /**
  48906. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48907. * @param effect The effect to update
  48908. * @param lightIndex The index of the light in the effect to update
  48909. * @returns The directional light
  48910. */
  48911. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48912. if (this.computeTransformedInformation()) {
  48913. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48914. return this;
  48915. }
  48916. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48917. return this;
  48918. };
  48919. /**
  48920. * Gets the minZ used for shadow according to both the scene and the light.
  48921. *
  48922. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48923. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48924. * @param activeCamera The camera we are returning the min for
  48925. * @returns the depth min z
  48926. */
  48927. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48928. return 1;
  48929. };
  48930. /**
  48931. * Gets the maxZ used for shadow according to both the scene and the light.
  48932. *
  48933. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48934. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48935. * @param activeCamera The camera we are returning the max for
  48936. * @returns the depth max z
  48937. */
  48938. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48939. return 1;
  48940. };
  48941. __decorate([
  48942. BABYLON.serialize()
  48943. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48944. __decorate([
  48945. BABYLON.serialize()
  48946. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48947. __decorate([
  48948. BABYLON.serialize()
  48949. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48950. return DirectionalLight;
  48951. }(BABYLON.ShadowLight));
  48952. BABYLON.DirectionalLight = DirectionalLight;
  48953. })(BABYLON || (BABYLON = {}));
  48954. //# sourceMappingURL=babylon.directionalLight.js.map
  48955. var BABYLON;
  48956. (function (BABYLON) {
  48957. /**
  48958. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48959. * These values define a cone of light starting from the position, emitting toward the direction.
  48960. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48961. * and the exponent defines the speed of the decay of the light with distance (reach).
  48962. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48963. */
  48964. var SpotLight = /** @class */ (function (_super) {
  48965. __extends(SpotLight, _super);
  48966. /**
  48967. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48968. * It can cast shadows.
  48969. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48970. * @param name The light friendly name
  48971. * @param position The position of the spot light in the scene
  48972. * @param direction The direction of the light in the scene
  48973. * @param angle The cone angle of the light in Radians
  48974. * @param exponent The light decay speed with the distance from the emission spot
  48975. * @param scene The scene the lights belongs to
  48976. */
  48977. function SpotLight(name, position, direction, angle, exponent, scene) {
  48978. var _this = _super.call(this, name, scene) || this;
  48979. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48980. _this._projectionTextureLightNear = 1e-6;
  48981. _this._projectionTextureLightFar = 1000.0;
  48982. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48983. _this._projectionTextureViewLightDirty = true;
  48984. _this._projectionTextureProjectionLightDirty = true;
  48985. _this._projectionTextureDirty = true;
  48986. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48987. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48988. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48989. _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);
  48990. _this.position = position;
  48991. _this.direction = direction;
  48992. _this.angle = angle;
  48993. _this.exponent = exponent;
  48994. return _this;
  48995. }
  48996. Object.defineProperty(SpotLight.prototype, "angle", {
  48997. /**
  48998. * Gets the cone angle of the spot light in Radians.
  48999. */
  49000. get: function () {
  49001. return this._angle;
  49002. },
  49003. /**
  49004. * Sets the cone angle of the spot light in Radians.
  49005. */
  49006. set: function (value) {
  49007. this._angle = value;
  49008. this._projectionTextureProjectionLightDirty = true;
  49009. this.forceProjectionMatrixCompute();
  49010. },
  49011. enumerable: true,
  49012. configurable: true
  49013. });
  49014. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49015. /**
  49016. * Allows scaling the angle of the light for shadow generation only.
  49017. */
  49018. get: function () {
  49019. return this._shadowAngleScale;
  49020. },
  49021. /**
  49022. * Allows scaling the angle of the light for shadow generation only.
  49023. */
  49024. set: function (value) {
  49025. this._shadowAngleScale = value;
  49026. this.forceProjectionMatrixCompute();
  49027. },
  49028. enumerable: true,
  49029. configurable: true
  49030. });
  49031. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49032. /**
  49033. * Allows reading the projecton texture
  49034. */
  49035. get: function () {
  49036. return this._projectionTextureMatrix;
  49037. },
  49038. enumerable: true,
  49039. configurable: true
  49040. });
  49041. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49042. /**
  49043. * Gets the near clip of the Spotlight for texture projection.
  49044. */
  49045. get: function () {
  49046. return this._projectionTextureLightNear;
  49047. },
  49048. /**
  49049. * Sets the near clip of the Spotlight for texture projection.
  49050. */
  49051. set: function (value) {
  49052. this._projectionTextureLightNear = value;
  49053. this._projectionTextureProjectionLightDirty = true;
  49054. },
  49055. enumerable: true,
  49056. configurable: true
  49057. });
  49058. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49059. /**
  49060. * Gets the far clip of the Spotlight for texture projection.
  49061. */
  49062. get: function () {
  49063. return this._projectionTextureLightFar;
  49064. },
  49065. /**
  49066. * Sets the far clip of the Spotlight for texture projection.
  49067. */
  49068. set: function (value) {
  49069. this._projectionTextureLightFar = value;
  49070. this._projectionTextureProjectionLightDirty = true;
  49071. },
  49072. enumerable: true,
  49073. configurable: true
  49074. });
  49075. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49076. /**
  49077. * Gets the Up vector of the Spotlight for texture projection.
  49078. */
  49079. get: function () {
  49080. return this._projectionTextureUpDirection;
  49081. },
  49082. /**
  49083. * Sets the Up vector of the Spotlight for texture projection.
  49084. */
  49085. set: function (value) {
  49086. this._projectionTextureUpDirection = value;
  49087. this._projectionTextureProjectionLightDirty = true;
  49088. },
  49089. enumerable: true,
  49090. configurable: true
  49091. });
  49092. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49093. /**
  49094. * Gets the projection texture of the light.
  49095. */
  49096. get: function () {
  49097. return this._projectionTexture;
  49098. },
  49099. /**
  49100. * Sets the projection texture of the light.
  49101. */
  49102. set: function (value) {
  49103. this._projectionTexture = value;
  49104. this._projectionTextureDirty = true;
  49105. },
  49106. enumerable: true,
  49107. configurable: true
  49108. });
  49109. /**
  49110. * Returns the string "SpotLight".
  49111. * @returns the class name
  49112. */
  49113. SpotLight.prototype.getClassName = function () {
  49114. return "SpotLight";
  49115. };
  49116. /**
  49117. * Returns the integer 2.
  49118. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49119. */
  49120. SpotLight.prototype.getTypeID = function () {
  49121. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49122. };
  49123. /**
  49124. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49125. */
  49126. SpotLight.prototype._setDirection = function (value) {
  49127. _super.prototype._setDirection.call(this, value);
  49128. this._projectionTextureViewLightDirty = true;
  49129. };
  49130. /**
  49131. * Overrides the position setter to recompute the projection texture view light Matrix.
  49132. */
  49133. SpotLight.prototype._setPosition = function (value) {
  49134. _super.prototype._setPosition.call(this, value);
  49135. this._projectionTextureViewLightDirty = true;
  49136. };
  49137. /**
  49138. * 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.
  49139. * Returns the SpotLight.
  49140. */
  49141. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49142. var activeCamera = this.getScene().activeCamera;
  49143. if (!activeCamera) {
  49144. return;
  49145. }
  49146. this._shadowAngleScale = this._shadowAngleScale || 1;
  49147. var angle = this._shadowAngleScale * this._angle;
  49148. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49149. };
  49150. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49151. this._projectionTextureViewLightDirty = false;
  49152. this._projectionTextureDirty = true;
  49153. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49154. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49155. };
  49156. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49157. this._projectionTextureProjectionLightDirty = false;
  49158. this._projectionTextureDirty = true;
  49159. var light_far = this.projectionTextureLightFar;
  49160. var light_near = this.projectionTextureLightNear;
  49161. var P = light_far / (light_far - light_near);
  49162. var Q = -P * light_near;
  49163. var S = 1.0 / Math.tan(this._angle / 2.0);
  49164. var A = 1.0;
  49165. 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);
  49166. };
  49167. /**
  49168. * Main function for light texture projection matrix computing.
  49169. */
  49170. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49171. this._projectionTextureDirty = false;
  49172. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49173. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49174. };
  49175. SpotLight.prototype._buildUniformLayout = function () {
  49176. this._uniformBuffer.addUniform("vLightData", 4);
  49177. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49178. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49179. this._uniformBuffer.addUniform("vLightDirection", 3);
  49180. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49181. this._uniformBuffer.addUniform("depthValues", 2);
  49182. this._uniformBuffer.create();
  49183. };
  49184. /**
  49185. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49186. * @param effect The effect to update
  49187. * @param lightIndex The index of the light in the effect to update
  49188. * @returns The spot light
  49189. */
  49190. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49191. var normalizeDirection;
  49192. if (this.computeTransformedInformation()) {
  49193. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49194. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49195. }
  49196. else {
  49197. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49198. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49199. }
  49200. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49201. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49202. if (this._projectionTextureViewLightDirty) {
  49203. this._computeProjectionTextureViewLightMatrix();
  49204. }
  49205. if (this._projectionTextureProjectionLightDirty) {
  49206. this._computeProjectionTextureProjectionLightMatrix();
  49207. }
  49208. if (this._projectionTextureDirty) {
  49209. this._computeProjectionTextureMatrix();
  49210. }
  49211. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49212. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49213. }
  49214. return this;
  49215. };
  49216. /**
  49217. * Disposes the light and the associated resources.
  49218. */
  49219. SpotLight.prototype.dispose = function () {
  49220. _super.prototype.dispose.call(this);
  49221. if (this._projectionTexture) {
  49222. this._projectionTexture.dispose();
  49223. }
  49224. };
  49225. __decorate([
  49226. BABYLON.serialize()
  49227. ], SpotLight.prototype, "angle", null);
  49228. __decorate([
  49229. BABYLON.serialize()
  49230. ], SpotLight.prototype, "shadowAngleScale", null);
  49231. __decorate([
  49232. BABYLON.serialize()
  49233. ], SpotLight.prototype, "exponent", void 0);
  49234. __decorate([
  49235. BABYLON.serialize()
  49236. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49237. __decorate([
  49238. BABYLON.serialize()
  49239. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49240. __decorate([
  49241. BABYLON.serialize()
  49242. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49243. __decorate([
  49244. BABYLON.serializeAsTexture("projectedLightTexture")
  49245. ], SpotLight.prototype, "_projectionTexture", void 0);
  49246. return SpotLight;
  49247. }(BABYLON.ShadowLight));
  49248. BABYLON.SpotLight = SpotLight;
  49249. })(BABYLON || (BABYLON = {}));
  49250. //# sourceMappingURL=babylon.spotLight.js.map
  49251. var BABYLON;
  49252. (function (BABYLON) {
  49253. /**
  49254. * Class used to override all child animations of a given target
  49255. */
  49256. var AnimationPropertiesOverride = /** @class */ (function () {
  49257. function AnimationPropertiesOverride() {
  49258. /**
  49259. * Gets or sets a value indicating if animation blending must be used
  49260. */
  49261. this.enableBlending = false;
  49262. /**
  49263. * Gets or sets the blending speed to use when enableBlending is true
  49264. */
  49265. this.blendingSpeed = 0.01;
  49266. /**
  49267. * Gets or sets the default loop mode to use
  49268. */
  49269. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49270. }
  49271. return AnimationPropertiesOverride;
  49272. }());
  49273. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49274. })(BABYLON || (BABYLON = {}));
  49275. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49276. var BABYLON;
  49277. (function (BABYLON) {
  49278. /**
  49279. * Represents the range of an animation
  49280. */
  49281. var AnimationRange = /** @class */ (function () {
  49282. /**
  49283. * Initializes the range of an animation
  49284. * @param name The name of the animation range
  49285. * @param from The starting frame of the animation
  49286. * @param to The ending frame of the animation
  49287. */
  49288. function AnimationRange(
  49289. /**The name of the animation range**/
  49290. name,
  49291. /**The starting frame of the animation */
  49292. from,
  49293. /**The ending frame of the animation*/
  49294. to) {
  49295. this.name = name;
  49296. this.from = from;
  49297. this.to = to;
  49298. }
  49299. /**
  49300. * Makes a copy of the animation range
  49301. * @returns A copy of the animation range
  49302. */
  49303. AnimationRange.prototype.clone = function () {
  49304. return new AnimationRange(this.name, this.from, this.to);
  49305. };
  49306. return AnimationRange;
  49307. }());
  49308. BABYLON.AnimationRange = AnimationRange;
  49309. /**
  49310. * Composed of a frame, and an action function
  49311. */
  49312. var AnimationEvent = /** @class */ (function () {
  49313. /**
  49314. * Initializes the animation event
  49315. * @param frame The frame for which the event is triggered
  49316. * @param action The event to perform when triggered
  49317. * @param onlyOnce Specifies if the event should be triggered only once
  49318. */
  49319. function AnimationEvent(
  49320. /** The frame for which the event is triggered **/
  49321. frame,
  49322. /** The event to perform when triggered **/
  49323. action,
  49324. /** Specifies if the event should be triggered only once**/
  49325. onlyOnce) {
  49326. this.frame = frame;
  49327. this.action = action;
  49328. this.onlyOnce = onlyOnce;
  49329. /**
  49330. * Specifies if the animation event is done
  49331. */
  49332. this.isDone = false;
  49333. }
  49334. /** @hidden */
  49335. AnimationEvent.prototype._clone = function () {
  49336. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49337. };
  49338. return AnimationEvent;
  49339. }());
  49340. BABYLON.AnimationEvent = AnimationEvent;
  49341. /**
  49342. * A cursor which tracks a point on a path
  49343. */
  49344. var PathCursor = /** @class */ (function () {
  49345. /**
  49346. * Initializes the path cursor
  49347. * @param path The path to track
  49348. */
  49349. function PathCursor(path) {
  49350. this.path = path;
  49351. /**
  49352. * Stores path cursor callbacks for when an onchange event is triggered
  49353. */
  49354. this._onchange = new Array();
  49355. /**
  49356. * The value of the path cursor
  49357. */
  49358. this.value = 0;
  49359. /**
  49360. * The animation array of the path cursor
  49361. */
  49362. this.animations = new Array();
  49363. }
  49364. /**
  49365. * Gets the cursor point on the path
  49366. * @returns A point on the path cursor at the cursor location
  49367. */
  49368. PathCursor.prototype.getPoint = function () {
  49369. var point = this.path.getPointAtLengthPosition(this.value);
  49370. return new BABYLON.Vector3(point.x, 0, point.y);
  49371. };
  49372. /**
  49373. * Moves the cursor ahead by the step amount
  49374. * @param step The amount to move the cursor forward
  49375. * @returns This path cursor
  49376. */
  49377. PathCursor.prototype.moveAhead = function (step) {
  49378. if (step === void 0) { step = 0.002; }
  49379. this.move(step);
  49380. return this;
  49381. };
  49382. /**
  49383. * Moves the cursor behind by the step amount
  49384. * @param step The amount to move the cursor back
  49385. * @returns This path cursor
  49386. */
  49387. PathCursor.prototype.moveBack = function (step) {
  49388. if (step === void 0) { step = 0.002; }
  49389. this.move(-step);
  49390. return this;
  49391. };
  49392. /**
  49393. * Moves the cursor by the step amount
  49394. * If the step amount is greater than one, an exception is thrown
  49395. * @param step The amount to move the cursor
  49396. * @returns This path cursor
  49397. */
  49398. PathCursor.prototype.move = function (step) {
  49399. if (Math.abs(step) > 1) {
  49400. throw "step size should be less than 1.";
  49401. }
  49402. this.value += step;
  49403. this.ensureLimits();
  49404. this.raiseOnChange();
  49405. return this;
  49406. };
  49407. /**
  49408. * Ensures that the value is limited between zero and one
  49409. * @returns This path cursor
  49410. */
  49411. PathCursor.prototype.ensureLimits = function () {
  49412. while (this.value > 1) {
  49413. this.value -= 1;
  49414. }
  49415. while (this.value < 0) {
  49416. this.value += 1;
  49417. }
  49418. return this;
  49419. };
  49420. /**
  49421. * Runs onchange callbacks on change (used by the animation engine)
  49422. * @returns This path cursor
  49423. */
  49424. PathCursor.prototype.raiseOnChange = function () {
  49425. var _this = this;
  49426. this._onchange.forEach(function (f) { return f(_this); });
  49427. return this;
  49428. };
  49429. /**
  49430. * Executes a function on change
  49431. * @param f A path cursor onchange callback
  49432. * @returns This path cursor
  49433. */
  49434. PathCursor.prototype.onchange = function (f) {
  49435. this._onchange.push(f);
  49436. return this;
  49437. };
  49438. return PathCursor;
  49439. }());
  49440. BABYLON.PathCursor = PathCursor;
  49441. /**
  49442. * Enum for the animation key frame interpolation type
  49443. */
  49444. var AnimationKeyInterpolation;
  49445. (function (AnimationKeyInterpolation) {
  49446. /**
  49447. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49448. */
  49449. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49450. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49451. /**
  49452. * Class used to store any kind of animation
  49453. */
  49454. var Animation = /** @class */ (function () {
  49455. /**
  49456. * Initializes the animation
  49457. * @param name Name of the animation
  49458. * @param targetProperty Property to animate
  49459. * @param framePerSecond The frames per second of the animation
  49460. * @param dataType The data type of the animation
  49461. * @param loopMode The loop mode of the animation
  49462. * @param enableBlendings Specifies if blending should be enabled
  49463. */
  49464. function Animation(
  49465. /**Name of the animation */
  49466. name,
  49467. /**Property to animate */
  49468. targetProperty,
  49469. /**The frames per second of the animation */
  49470. framePerSecond,
  49471. /**The data type of the animation */
  49472. dataType,
  49473. /**The loop mode of the animation */
  49474. loopMode,
  49475. /**Specifies if blending should be enabled */
  49476. enableBlending) {
  49477. this.name = name;
  49478. this.targetProperty = targetProperty;
  49479. this.framePerSecond = framePerSecond;
  49480. this.dataType = dataType;
  49481. this.loopMode = loopMode;
  49482. this.enableBlending = enableBlending;
  49483. /**
  49484. * @hidden Internal use only
  49485. */
  49486. this._runtimeAnimations = new Array();
  49487. /**
  49488. * The set of event that will be linked to this animation
  49489. */
  49490. this._events = new Array();
  49491. /**
  49492. * Stores the blending speed of the animation
  49493. */
  49494. this.blendingSpeed = 0.01;
  49495. /**
  49496. * Stores the animation ranges for the animation
  49497. */
  49498. this._ranges = {};
  49499. this.targetPropertyPath = targetProperty.split(".");
  49500. this.dataType = dataType;
  49501. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49502. }
  49503. /**
  49504. * @hidden Internal use
  49505. */
  49506. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49507. var dataType = undefined;
  49508. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49509. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49510. }
  49511. else if (from instanceof BABYLON.Quaternion) {
  49512. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49513. }
  49514. else if (from instanceof BABYLON.Vector3) {
  49515. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49516. }
  49517. else if (from instanceof BABYLON.Vector2) {
  49518. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49519. }
  49520. else if (from instanceof BABYLON.Color3) {
  49521. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49522. }
  49523. else if (from instanceof BABYLON.Size) {
  49524. dataType = Animation.ANIMATIONTYPE_SIZE;
  49525. }
  49526. if (dataType == undefined) {
  49527. return null;
  49528. }
  49529. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49530. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49531. animation.setKeys(keys);
  49532. if (easingFunction !== undefined) {
  49533. animation.setEasingFunction(easingFunction);
  49534. }
  49535. return animation;
  49536. };
  49537. /**
  49538. * Sets up an animation
  49539. * @param property The property to animate
  49540. * @param animationType The animation type to apply
  49541. * @param framePerSecond The frames per second of the animation
  49542. * @param easingFunction The easing function used in the animation
  49543. * @returns The created animation
  49544. */
  49545. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49546. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49547. animation.setEasingFunction(easingFunction);
  49548. return animation;
  49549. };
  49550. /**
  49551. * Create and start an animation on a node
  49552. * @param name defines the name of the global animation that will be run on all nodes
  49553. * @param node defines the root node where the animation will take place
  49554. * @param targetProperty defines property to animate
  49555. * @param framePerSecond defines the number of frame per second yo use
  49556. * @param totalFrame defines the number of frames in total
  49557. * @param from defines the initial value
  49558. * @param to defines the final value
  49559. * @param loopMode defines which loop mode you want to use (off by default)
  49560. * @param easingFunction defines the easing function to use (linear by default)
  49561. * @param onAnimationEnd defines the callback to call when animation end
  49562. * @returns the animatable created for this animation
  49563. */
  49564. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49565. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49566. if (!animation) {
  49567. return null;
  49568. }
  49569. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49570. };
  49571. /**
  49572. * Create and start an animation on a node and its descendants
  49573. * @param name defines the name of the global animation that will be run on all nodes
  49574. * @param node defines the root node where the animation will take place
  49575. * @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
  49576. * @param targetProperty defines property to animate
  49577. * @param framePerSecond defines the number of frame per second to use
  49578. * @param totalFrame defines the number of frames in total
  49579. * @param from defines the initial value
  49580. * @param to defines the final value
  49581. * @param loopMode defines which loop mode you want to use (off by default)
  49582. * @param easingFunction defines the easing function to use (linear by default)
  49583. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49584. * @returns the list of animatables created for all nodes
  49585. * @example https://www.babylonjs-playground.com/#MH0VLI
  49586. */
  49587. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49588. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49589. if (!animation) {
  49590. return null;
  49591. }
  49592. var scene = node.getScene();
  49593. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49594. };
  49595. /**
  49596. * Creates a new animation, merges it with the existing animations and starts it
  49597. * @param name Name of the animation
  49598. * @param node Node which contains the scene that begins the animations
  49599. * @param targetProperty Specifies which property to animate
  49600. * @param framePerSecond The frames per second of the animation
  49601. * @param totalFrame The total number of frames
  49602. * @param from The frame at the beginning of the animation
  49603. * @param to The frame at the end of the animation
  49604. * @param loopMode Specifies the loop mode of the animation
  49605. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49606. * @param onAnimationEnd Callback to run once the animation is complete
  49607. * @returns Nullable animation
  49608. */
  49609. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49610. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49611. if (!animation) {
  49612. return null;
  49613. }
  49614. node.animations.push(animation);
  49615. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49616. };
  49617. /**
  49618. * Transition property of an host to the target Value
  49619. * @param property The property to transition
  49620. * @param targetValue The target Value of the property
  49621. * @param host The object where the property to animate belongs
  49622. * @param scene Scene used to run the animation
  49623. * @param frameRate Framerate (in frame/s) to use
  49624. * @param transition The transition type we want to use
  49625. * @param duration The duration of the animation, in milliseconds
  49626. * @param onAnimationEnd Callback trigger at the end of the animation
  49627. * @returns Nullable animation
  49628. */
  49629. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49630. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49631. if (duration <= 0) {
  49632. host[property] = targetValue;
  49633. if (onAnimationEnd) {
  49634. onAnimationEnd();
  49635. }
  49636. return null;
  49637. }
  49638. var endFrame = frameRate * (duration / 1000);
  49639. transition.setKeys([{
  49640. frame: 0,
  49641. value: host[property].clone ? host[property].clone() : host[property]
  49642. },
  49643. {
  49644. frame: endFrame,
  49645. value: targetValue
  49646. }]);
  49647. if (!host.animations) {
  49648. host.animations = [];
  49649. }
  49650. host.animations.push(transition);
  49651. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49652. animation.onAnimationEnd = onAnimationEnd;
  49653. return animation;
  49654. };
  49655. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49656. /**
  49657. * Return the array of runtime animations currently using this animation
  49658. */
  49659. get: function () {
  49660. return this._runtimeAnimations;
  49661. },
  49662. enumerable: true,
  49663. configurable: true
  49664. });
  49665. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49666. /**
  49667. * Specifies if any of the runtime animations are currently running
  49668. */
  49669. get: function () {
  49670. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49671. var runtimeAnimation = _a[_i];
  49672. if (!runtimeAnimation.isStopped) {
  49673. return true;
  49674. }
  49675. }
  49676. return false;
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. // Methods
  49682. /**
  49683. * Converts the animation to a string
  49684. * @param fullDetails support for multiple levels of logging within scene loading
  49685. * @returns String form of the animation
  49686. */
  49687. Animation.prototype.toString = function (fullDetails) {
  49688. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49689. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49690. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49691. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49692. if (fullDetails) {
  49693. ret += ", Ranges: {";
  49694. var first = true;
  49695. for (var name in this._ranges) {
  49696. if (first) {
  49697. ret += ", ";
  49698. first = false;
  49699. }
  49700. ret += name;
  49701. }
  49702. ret += "}";
  49703. }
  49704. return ret;
  49705. };
  49706. /**
  49707. * Add an event to this animation
  49708. * @param event Event to add
  49709. */
  49710. Animation.prototype.addEvent = function (event) {
  49711. this._events.push(event);
  49712. };
  49713. /**
  49714. * Remove all events found at the given frame
  49715. * @param frame The frame to remove events from
  49716. */
  49717. Animation.prototype.removeEvents = function (frame) {
  49718. for (var index = 0; index < this._events.length; index++) {
  49719. if (this._events[index].frame === frame) {
  49720. this._events.splice(index, 1);
  49721. index--;
  49722. }
  49723. }
  49724. };
  49725. /**
  49726. * Retrieves all the events from the animation
  49727. * @returns Events from the animation
  49728. */
  49729. Animation.prototype.getEvents = function () {
  49730. return this._events;
  49731. };
  49732. /**
  49733. * Creates an animation range
  49734. * @param name Name of the animation range
  49735. * @param from Starting frame of the animation range
  49736. * @param to Ending frame of the animation
  49737. */
  49738. Animation.prototype.createRange = function (name, from, to) {
  49739. // check name not already in use; could happen for bones after serialized
  49740. if (!this._ranges[name]) {
  49741. this._ranges[name] = new AnimationRange(name, from, to);
  49742. }
  49743. };
  49744. /**
  49745. * Deletes an animation range by name
  49746. * @param name Name of the animation range to delete
  49747. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49748. */
  49749. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49750. if (deleteFrames === void 0) { deleteFrames = true; }
  49751. var range = this._ranges[name];
  49752. if (!range) {
  49753. return;
  49754. }
  49755. if (deleteFrames) {
  49756. var from = range.from;
  49757. var to = range.to;
  49758. // this loop MUST go high to low for multiple splices to work
  49759. for (var key = this._keys.length - 1; key >= 0; key--) {
  49760. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49761. this._keys.splice(key, 1);
  49762. }
  49763. }
  49764. }
  49765. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49766. };
  49767. /**
  49768. * Gets the animation range by name, or null if not defined
  49769. * @param name Name of the animation range
  49770. * @returns Nullable animation range
  49771. */
  49772. Animation.prototype.getRange = function (name) {
  49773. return this._ranges[name];
  49774. };
  49775. /**
  49776. * Gets the key frames from the animation
  49777. * @returns The key frames of the animation
  49778. */
  49779. Animation.prototype.getKeys = function () {
  49780. return this._keys;
  49781. };
  49782. /**
  49783. * Gets the highest frame rate of the animation
  49784. * @returns Highest frame rate of the animation
  49785. */
  49786. Animation.prototype.getHighestFrame = function () {
  49787. var ret = 0;
  49788. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49789. if (ret < this._keys[key].frame) {
  49790. ret = this._keys[key].frame;
  49791. }
  49792. }
  49793. return ret;
  49794. };
  49795. /**
  49796. * Gets the easing function of the animation
  49797. * @returns Easing function of the animation
  49798. */
  49799. Animation.prototype.getEasingFunction = function () {
  49800. return this._easingFunction;
  49801. };
  49802. /**
  49803. * Sets the easing function of the animation
  49804. * @param easingFunction A custom mathematical formula for animation
  49805. */
  49806. Animation.prototype.setEasingFunction = function (easingFunction) {
  49807. this._easingFunction = easingFunction;
  49808. };
  49809. /**
  49810. * Interpolates a scalar linearly
  49811. * @param startValue Start value of the animation curve
  49812. * @param endValue End value of the animation curve
  49813. * @param gradient Scalar amount to interpolate
  49814. * @returns Interpolated scalar value
  49815. */
  49816. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49817. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49818. };
  49819. /**
  49820. * Interpolates a scalar cubically
  49821. * @param startValue Start value of the animation curve
  49822. * @param outTangent End tangent of the animation
  49823. * @param endValue End value of the animation curve
  49824. * @param inTangent Start tangent of the animation curve
  49825. * @param gradient Scalar amount to interpolate
  49826. * @returns Interpolated scalar value
  49827. */
  49828. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49829. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49830. };
  49831. /**
  49832. * Interpolates a quaternion using a spherical linear interpolation
  49833. * @param startValue Start value of the animation curve
  49834. * @param endValue End value of the animation curve
  49835. * @param gradient Scalar amount to interpolate
  49836. * @returns Interpolated quaternion value
  49837. */
  49838. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49839. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49840. };
  49841. /**
  49842. * Interpolates a quaternion cubically
  49843. * @param startValue Start value of the animation curve
  49844. * @param outTangent End tangent of the animation curve
  49845. * @param endValue End value of the animation curve
  49846. * @param inTangent Start tangent of the animation curve
  49847. * @param gradient Scalar amount to interpolate
  49848. * @returns Interpolated quaternion value
  49849. */
  49850. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49851. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49852. };
  49853. /**
  49854. * Interpolates a Vector3 linearl
  49855. * @param startValue Start value of the animation curve
  49856. * @param endValue End value of the animation curve
  49857. * @param gradient Scalar amount to interpolate
  49858. * @returns Interpolated scalar value
  49859. */
  49860. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49861. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49862. };
  49863. /**
  49864. * Interpolates a Vector3 cubically
  49865. * @param startValue Start value of the animation curve
  49866. * @param outTangent End tangent of the animation
  49867. * @param endValue End value of the animation curve
  49868. * @param inTangent Start tangent of the animation curve
  49869. * @param gradient Scalar amount to interpolate
  49870. * @returns InterpolatedVector3 value
  49871. */
  49872. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49873. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49874. };
  49875. /**
  49876. * Interpolates a Vector2 linearly
  49877. * @param startValue Start value of the animation curve
  49878. * @param endValue End value of the animation curve
  49879. * @param gradient Scalar amount to interpolate
  49880. * @returns Interpolated Vector2 value
  49881. */
  49882. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49883. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49884. };
  49885. /**
  49886. * Interpolates a Vector2 cubically
  49887. * @param startValue Start value of the animation curve
  49888. * @param outTangent End tangent of the animation
  49889. * @param endValue End value of the animation curve
  49890. * @param inTangent Start tangent of the animation curve
  49891. * @param gradient Scalar amount to interpolate
  49892. * @returns Interpolated Vector2 value
  49893. */
  49894. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49895. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49896. };
  49897. /**
  49898. * Interpolates a size linearly
  49899. * @param startValue Start value of the animation curve
  49900. * @param endValue End value of the animation curve
  49901. * @param gradient Scalar amount to interpolate
  49902. * @returns Interpolated Size value
  49903. */
  49904. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49905. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49906. };
  49907. /**
  49908. * Interpolates a Color3 linearly
  49909. * @param startValue Start value of the animation curve
  49910. * @param endValue End value of the animation curve
  49911. * @param gradient Scalar amount to interpolate
  49912. * @returns Interpolated Color3 value
  49913. */
  49914. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49915. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49916. };
  49917. /**
  49918. * @hidden Internal use only
  49919. */
  49920. Animation.prototype._getKeyValue = function (value) {
  49921. if (typeof value === "function") {
  49922. return value();
  49923. }
  49924. return value;
  49925. };
  49926. /**
  49927. * @hidden Internal use only
  49928. */
  49929. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49930. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49931. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49932. }
  49933. var keys = this.getKeys();
  49934. // Try to get a hash to find the right key
  49935. 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));
  49936. if (keys[startKeyIndex].frame >= currentFrame) {
  49937. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49938. startKeyIndex--;
  49939. }
  49940. }
  49941. for (var key = startKeyIndex; key < keys.length; key++) {
  49942. var endKey = keys[key + 1];
  49943. if (endKey.frame >= currentFrame) {
  49944. var startKey = keys[key];
  49945. var startValue = this._getKeyValue(startKey.value);
  49946. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49947. return startValue;
  49948. }
  49949. var endValue = this._getKeyValue(endKey.value);
  49950. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49951. var frameDelta = endKey.frame - startKey.frame;
  49952. // gradient : percent of currentFrame between the frame inf and the frame sup
  49953. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49954. // check for easingFunction and correction of gradient
  49955. var easingFunction = this.getEasingFunction();
  49956. if (easingFunction != null) {
  49957. gradient = easingFunction.ease(gradient);
  49958. }
  49959. switch (this.dataType) {
  49960. // Float
  49961. case Animation.ANIMATIONTYPE_FLOAT:
  49962. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49963. switch (loopMode) {
  49964. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49965. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49966. return floatValue;
  49967. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49968. return offsetValue * repeatCount + floatValue;
  49969. }
  49970. break;
  49971. // Quaternion
  49972. case Animation.ANIMATIONTYPE_QUATERNION:
  49973. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49974. switch (loopMode) {
  49975. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49976. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49977. return quatValue;
  49978. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49979. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49980. }
  49981. return quatValue;
  49982. // Vector3
  49983. case Animation.ANIMATIONTYPE_VECTOR3:
  49984. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49985. switch (loopMode) {
  49986. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49987. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49988. return vec3Value;
  49989. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49990. return vec3Value.add(offsetValue.scale(repeatCount));
  49991. }
  49992. // Vector2
  49993. case Animation.ANIMATIONTYPE_VECTOR2:
  49994. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49995. switch (loopMode) {
  49996. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49997. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49998. return vec2Value;
  49999. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50000. return vec2Value.add(offsetValue.scale(repeatCount));
  50001. }
  50002. // Size
  50003. case Animation.ANIMATIONTYPE_SIZE:
  50004. switch (loopMode) {
  50005. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50006. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50007. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50008. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50009. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50010. }
  50011. // Color3
  50012. case Animation.ANIMATIONTYPE_COLOR3:
  50013. switch (loopMode) {
  50014. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50015. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50016. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50017. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50018. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50019. }
  50020. // Matrix
  50021. case Animation.ANIMATIONTYPE_MATRIX:
  50022. switch (loopMode) {
  50023. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50024. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50025. if (Animation.AllowMatricesInterpolation) {
  50026. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50027. }
  50028. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50029. return startValue;
  50030. }
  50031. default:
  50032. break;
  50033. }
  50034. break;
  50035. }
  50036. }
  50037. return this._getKeyValue(keys[keys.length - 1].value);
  50038. };
  50039. /**
  50040. * Defines the function to use to interpolate matrices
  50041. * @param startValue defines the start matrix
  50042. * @param endValue defines the end matrix
  50043. * @param gradient defines the gradient between both matrices
  50044. * @param result defines an optional target matrix where to store the interpolation
  50045. * @returns the interpolated matrix
  50046. */
  50047. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50048. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50049. if (result) {
  50050. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50051. return result;
  50052. }
  50053. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50054. }
  50055. if (result) {
  50056. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50057. return result;
  50058. }
  50059. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50060. };
  50061. /**
  50062. * Makes a copy of the animation
  50063. * @returns Cloned animation
  50064. */
  50065. Animation.prototype.clone = function () {
  50066. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50067. clone.enableBlending = this.enableBlending;
  50068. clone.blendingSpeed = this.blendingSpeed;
  50069. if (this._keys) {
  50070. clone.setKeys(this._keys);
  50071. }
  50072. if (this._ranges) {
  50073. clone._ranges = {};
  50074. for (var name in this._ranges) {
  50075. var range = this._ranges[name];
  50076. if (!range) {
  50077. continue;
  50078. }
  50079. clone._ranges[name] = range.clone();
  50080. }
  50081. }
  50082. return clone;
  50083. };
  50084. /**
  50085. * Sets the key frames of the animation
  50086. * @param values The animation key frames to set
  50087. */
  50088. Animation.prototype.setKeys = function (values) {
  50089. this._keys = values.slice(0);
  50090. };
  50091. /**
  50092. * Serializes the animation to an object
  50093. * @returns Serialized object
  50094. */
  50095. Animation.prototype.serialize = function () {
  50096. var serializationObject = {};
  50097. serializationObject.name = this.name;
  50098. serializationObject.property = this.targetProperty;
  50099. serializationObject.framePerSecond = this.framePerSecond;
  50100. serializationObject.dataType = this.dataType;
  50101. serializationObject.loopBehavior = this.loopMode;
  50102. serializationObject.enableBlending = this.enableBlending;
  50103. serializationObject.blendingSpeed = this.blendingSpeed;
  50104. var dataType = this.dataType;
  50105. serializationObject.keys = [];
  50106. var keys = this.getKeys();
  50107. for (var index = 0; index < keys.length; index++) {
  50108. var animationKey = keys[index];
  50109. var key = {};
  50110. key.frame = animationKey.frame;
  50111. switch (dataType) {
  50112. case Animation.ANIMATIONTYPE_FLOAT:
  50113. key.values = [animationKey.value];
  50114. break;
  50115. case Animation.ANIMATIONTYPE_QUATERNION:
  50116. case Animation.ANIMATIONTYPE_MATRIX:
  50117. case Animation.ANIMATIONTYPE_VECTOR3:
  50118. case Animation.ANIMATIONTYPE_COLOR3:
  50119. key.values = animationKey.value.asArray();
  50120. break;
  50121. }
  50122. serializationObject.keys.push(key);
  50123. }
  50124. serializationObject.ranges = [];
  50125. for (var name in this._ranges) {
  50126. var source = this._ranges[name];
  50127. if (!source) {
  50128. continue;
  50129. }
  50130. var range = {};
  50131. range.name = name;
  50132. range.from = source.from;
  50133. range.to = source.to;
  50134. serializationObject.ranges.push(range);
  50135. }
  50136. return serializationObject;
  50137. };
  50138. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50139. /**
  50140. * Get the float animation type
  50141. */
  50142. get: function () {
  50143. return Animation._ANIMATIONTYPE_FLOAT;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50149. /**
  50150. * Get the Vector3 animation type
  50151. */
  50152. get: function () {
  50153. return Animation._ANIMATIONTYPE_VECTOR3;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50159. /**
  50160. * Get the Vectpr2 animation type
  50161. */
  50162. get: function () {
  50163. return Animation._ANIMATIONTYPE_VECTOR2;
  50164. },
  50165. enumerable: true,
  50166. configurable: true
  50167. });
  50168. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50169. /**
  50170. * Get the Size animation type
  50171. */
  50172. get: function () {
  50173. return Animation._ANIMATIONTYPE_SIZE;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50179. /**
  50180. * Get the Quaternion animation type
  50181. */
  50182. get: function () {
  50183. return Animation._ANIMATIONTYPE_QUATERNION;
  50184. },
  50185. enumerable: true,
  50186. configurable: true
  50187. });
  50188. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50189. /**
  50190. * Get the Matrix animation type
  50191. */
  50192. get: function () {
  50193. return Animation._ANIMATIONTYPE_MATRIX;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50199. /**
  50200. * Get the Color3 animation type
  50201. */
  50202. get: function () {
  50203. return Animation._ANIMATIONTYPE_COLOR3;
  50204. },
  50205. enumerable: true,
  50206. configurable: true
  50207. });
  50208. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50209. /**
  50210. * Get the Relative Loop Mode
  50211. */
  50212. get: function () {
  50213. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50214. },
  50215. enumerable: true,
  50216. configurable: true
  50217. });
  50218. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50219. /**
  50220. * Get the Cycle Loop Mode
  50221. */
  50222. get: function () {
  50223. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50224. },
  50225. enumerable: true,
  50226. configurable: true
  50227. });
  50228. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50229. /**
  50230. * Get the Constant Loop Mode
  50231. */
  50232. get: function () {
  50233. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50234. },
  50235. enumerable: true,
  50236. configurable: true
  50237. });
  50238. /** @hidden */
  50239. Animation._UniversalLerp = function (left, right, amount) {
  50240. var constructor = left.constructor;
  50241. if (constructor.Lerp) { // Lerp supported
  50242. return constructor.Lerp(left, right, amount);
  50243. }
  50244. else if (constructor.Slerp) { // Slerp supported
  50245. return constructor.Slerp(left, right, amount);
  50246. }
  50247. else if (left.toFixed) { // Number
  50248. return left * (1.0 - amount) + amount * right;
  50249. }
  50250. else { // Blending not supported
  50251. return right;
  50252. }
  50253. };
  50254. /**
  50255. * Parses an animation object and creates an animation
  50256. * @param parsedAnimation Parsed animation object
  50257. * @returns Animation object
  50258. */
  50259. Animation.Parse = function (parsedAnimation) {
  50260. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50261. var dataType = parsedAnimation.dataType;
  50262. var keys = [];
  50263. var data;
  50264. var index;
  50265. if (parsedAnimation.enableBlending) {
  50266. animation.enableBlending = parsedAnimation.enableBlending;
  50267. }
  50268. if (parsedAnimation.blendingSpeed) {
  50269. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50270. }
  50271. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50272. var key = parsedAnimation.keys[index];
  50273. var inTangent;
  50274. var outTangent;
  50275. switch (dataType) {
  50276. case Animation.ANIMATIONTYPE_FLOAT:
  50277. data = key.values[0];
  50278. if (key.values.length >= 1) {
  50279. inTangent = key.values[1];
  50280. }
  50281. if (key.values.length >= 2) {
  50282. outTangent = key.values[2];
  50283. }
  50284. break;
  50285. case Animation.ANIMATIONTYPE_QUATERNION:
  50286. data = BABYLON.Quaternion.FromArray(key.values);
  50287. if (key.values.length >= 8) {
  50288. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50289. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50290. inTangent = _inTangent;
  50291. }
  50292. }
  50293. if (key.values.length >= 12) {
  50294. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50295. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50296. outTangent = _outTangent;
  50297. }
  50298. }
  50299. break;
  50300. case Animation.ANIMATIONTYPE_MATRIX:
  50301. data = BABYLON.Matrix.FromArray(key.values);
  50302. break;
  50303. case Animation.ANIMATIONTYPE_COLOR3:
  50304. data = BABYLON.Color3.FromArray(key.values);
  50305. break;
  50306. case Animation.ANIMATIONTYPE_VECTOR3:
  50307. default:
  50308. data = BABYLON.Vector3.FromArray(key.values);
  50309. break;
  50310. }
  50311. var keyData = {};
  50312. keyData.frame = key.frame;
  50313. keyData.value = data;
  50314. if (inTangent != undefined) {
  50315. keyData.inTangent = inTangent;
  50316. }
  50317. if (outTangent != undefined) {
  50318. keyData.outTangent = outTangent;
  50319. }
  50320. keys.push(keyData);
  50321. }
  50322. animation.setKeys(keys);
  50323. if (parsedAnimation.ranges) {
  50324. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50325. data = parsedAnimation.ranges[index];
  50326. animation.createRange(data.name, data.from, data.to);
  50327. }
  50328. }
  50329. return animation;
  50330. };
  50331. /**
  50332. * Appends the serialized animations from the source animations
  50333. * @param source Source containing the animations
  50334. * @param destination Target to store the animations
  50335. */
  50336. Animation.AppendSerializedAnimations = function (source, destination) {
  50337. if (source.animations) {
  50338. destination.animations = [];
  50339. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50340. var animation = source.animations[animationIndex];
  50341. destination.animations.push(animation.serialize());
  50342. }
  50343. }
  50344. };
  50345. /**
  50346. * Use matrix interpolation instead of using direct key value when animating matrices
  50347. */
  50348. Animation.AllowMatricesInterpolation = false;
  50349. /**
  50350. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50351. */
  50352. Animation.AllowMatrixDecomposeForInterpolation = true;
  50353. // Statics
  50354. /**
  50355. * Float animation type
  50356. */
  50357. Animation._ANIMATIONTYPE_FLOAT = 0;
  50358. /**
  50359. * Vector3 animation type
  50360. */
  50361. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50362. /**
  50363. * Quaternion animation type
  50364. */
  50365. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50366. /**
  50367. * Matrix animation type
  50368. */
  50369. Animation._ANIMATIONTYPE_MATRIX = 3;
  50370. /**
  50371. * Color3 animation type
  50372. */
  50373. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50374. /**
  50375. * Vector2 animation type
  50376. */
  50377. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50378. /**
  50379. * Size animation type
  50380. */
  50381. Animation._ANIMATIONTYPE_SIZE = 6;
  50382. /**
  50383. * Relative Loop Mode
  50384. */
  50385. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50386. /**
  50387. * Cycle Loop Mode
  50388. */
  50389. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50390. /**
  50391. * Constant Loop Mode
  50392. */
  50393. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50394. return Animation;
  50395. }());
  50396. BABYLON.Animation = Animation;
  50397. })(BABYLON || (BABYLON = {}));
  50398. //# sourceMappingURL=babylon.animation.js.map
  50399. var BABYLON;
  50400. (function (BABYLON) {
  50401. /**
  50402. * This class defines the direct association between an animation and a target
  50403. */
  50404. var TargetedAnimation = /** @class */ (function () {
  50405. function TargetedAnimation() {
  50406. }
  50407. return TargetedAnimation;
  50408. }());
  50409. BABYLON.TargetedAnimation = TargetedAnimation;
  50410. /**
  50411. * Use this class to create coordinated animations on multiple targets
  50412. */
  50413. var AnimationGroup = /** @class */ (function () {
  50414. function AnimationGroup(name, scene) {
  50415. if (scene === void 0) { scene = null; }
  50416. this.name = name;
  50417. this._targetedAnimations = new Array();
  50418. this._animatables = new Array();
  50419. this._from = Number.MAX_VALUE;
  50420. this._to = -Number.MAX_VALUE;
  50421. this._speedRatio = 1;
  50422. this.onAnimationEndObservable = new BABYLON.Observable();
  50423. /**
  50424. * This observable will notify when all animations have ended.
  50425. */
  50426. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50427. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50428. this._scene.animationGroups.push(this);
  50429. }
  50430. Object.defineProperty(AnimationGroup.prototype, "from", {
  50431. /**
  50432. * Gets the first frame
  50433. */
  50434. get: function () {
  50435. return this._from;
  50436. },
  50437. enumerable: true,
  50438. configurable: true
  50439. });
  50440. Object.defineProperty(AnimationGroup.prototype, "to", {
  50441. /**
  50442. * Gets the last frame
  50443. */
  50444. get: function () {
  50445. return this._to;
  50446. },
  50447. enumerable: true,
  50448. configurable: true
  50449. });
  50450. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50451. /**
  50452. * Define if the animations are started
  50453. */
  50454. get: function () {
  50455. return this._isStarted;
  50456. },
  50457. enumerable: true,
  50458. configurable: true
  50459. });
  50460. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50461. /**
  50462. * Gets or sets the speed ratio to use for all animations
  50463. */
  50464. get: function () {
  50465. return this._speedRatio;
  50466. },
  50467. /**
  50468. * Gets or sets the speed ratio to use for all animations
  50469. */
  50470. set: function (value) {
  50471. if (this._speedRatio === value) {
  50472. return;
  50473. }
  50474. this._speedRatio = value;
  50475. for (var index = 0; index < this._animatables.length; index++) {
  50476. var animatable = this._animatables[index];
  50477. animatable.speedRatio = this._speedRatio;
  50478. }
  50479. },
  50480. enumerable: true,
  50481. configurable: true
  50482. });
  50483. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50484. /**
  50485. * Gets the targeted animations for this animation group
  50486. */
  50487. get: function () {
  50488. return this._targetedAnimations;
  50489. },
  50490. enumerable: true,
  50491. configurable: true
  50492. });
  50493. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50494. /**
  50495. * returning the list of animatables controlled by this animation group.
  50496. */
  50497. get: function () {
  50498. return this._animatables;
  50499. },
  50500. enumerable: true,
  50501. configurable: true
  50502. });
  50503. /**
  50504. * Add an animation (with its target) in the group
  50505. * @param animation defines the animation we want to add
  50506. * @param target defines the target of the animation
  50507. * @returns the {BABYLON.TargetedAnimation} object
  50508. */
  50509. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50510. var targetedAnimation = {
  50511. animation: animation,
  50512. target: target
  50513. };
  50514. var keys = animation.getKeys();
  50515. if (this._from > keys[0].frame) {
  50516. this._from = keys[0].frame;
  50517. }
  50518. if (this._to < keys[keys.length - 1].frame) {
  50519. this._to = keys[keys.length - 1].frame;
  50520. }
  50521. this._targetedAnimations.push(targetedAnimation);
  50522. return targetedAnimation;
  50523. };
  50524. /**
  50525. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50526. * It can add constant keys at begin or end
  50527. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50528. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50529. */
  50530. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50531. if (beginFrame === void 0) { beginFrame = null; }
  50532. if (endFrame === void 0) { endFrame = null; }
  50533. if (beginFrame == null)
  50534. beginFrame = this._from;
  50535. if (endFrame == null)
  50536. endFrame = this._to;
  50537. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50538. var targetedAnimation = this._targetedAnimations[index];
  50539. var keys = targetedAnimation.animation.getKeys();
  50540. var startKey = keys[0];
  50541. var endKey = keys[keys.length - 1];
  50542. if (startKey.frame > beginFrame) {
  50543. var newKey = {
  50544. frame: beginFrame,
  50545. value: startKey.value,
  50546. inTangent: startKey.inTangent,
  50547. outTangent: startKey.outTangent,
  50548. interpolation: startKey.interpolation
  50549. };
  50550. keys.splice(0, 0, newKey);
  50551. }
  50552. if (endKey.frame < endFrame) {
  50553. var newKey = {
  50554. frame: endFrame,
  50555. value: endKey.value,
  50556. inTangent: endKey.outTangent,
  50557. outTangent: endKey.outTangent,
  50558. interpolation: endKey.interpolation
  50559. };
  50560. keys.push(newKey);
  50561. }
  50562. }
  50563. this._from = beginFrame;
  50564. this._to = endFrame;
  50565. return this;
  50566. };
  50567. /**
  50568. * Start all animations on given targets
  50569. * @param loop defines if animations must loop
  50570. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50571. * @param from defines the from key (optional)
  50572. * @param to defines the to key (optional)
  50573. * @returns the current animation group
  50574. */
  50575. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50576. var _this = this;
  50577. if (loop === void 0) { loop = false; }
  50578. if (speedRatio === void 0) { speedRatio = 1; }
  50579. if (this._isStarted || this._targetedAnimations.length === 0) {
  50580. return this;
  50581. }
  50582. var _loop_1 = function (targetedAnimation) {
  50583. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50584. animatable.onAnimationEnd = function () {
  50585. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50586. _this._checkAnimationGroupEnded(animatable);
  50587. };
  50588. this_1._animatables.push(animatable);
  50589. };
  50590. var this_1 = this;
  50591. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50592. var targetedAnimation = _a[_i];
  50593. _loop_1(targetedAnimation);
  50594. }
  50595. this._speedRatio = speedRatio;
  50596. this._isStarted = true;
  50597. return this;
  50598. };
  50599. /**
  50600. * Pause all animations
  50601. */
  50602. AnimationGroup.prototype.pause = function () {
  50603. if (!this._isStarted) {
  50604. return this;
  50605. }
  50606. for (var index = 0; index < this._animatables.length; index++) {
  50607. var animatable = this._animatables[index];
  50608. animatable.pause();
  50609. }
  50610. return this;
  50611. };
  50612. /**
  50613. * Play all animations to initial state
  50614. * This function will start() the animations if they were not started or will restart() them if they were paused
  50615. * @param loop defines if animations must loop
  50616. */
  50617. AnimationGroup.prototype.play = function (loop) {
  50618. // only if all animatables are ready and exist
  50619. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50620. if (loop !== undefined) {
  50621. for (var index = 0; index < this._animatables.length; index++) {
  50622. var animatable = this._animatables[index];
  50623. animatable.loopAnimation = loop;
  50624. }
  50625. }
  50626. this.restart();
  50627. }
  50628. else {
  50629. this.stop();
  50630. this.start(loop, this._speedRatio);
  50631. }
  50632. return this;
  50633. };
  50634. /**
  50635. * Reset all animations to initial state
  50636. */
  50637. AnimationGroup.prototype.reset = function () {
  50638. if (!this._isStarted) {
  50639. return this;
  50640. }
  50641. for (var index = 0; index < this._animatables.length; index++) {
  50642. var animatable = this._animatables[index];
  50643. animatable.reset();
  50644. }
  50645. return this;
  50646. };
  50647. /**
  50648. * Restart animations from key 0
  50649. */
  50650. AnimationGroup.prototype.restart = function () {
  50651. if (!this._isStarted) {
  50652. return this;
  50653. }
  50654. for (var index = 0; index < this._animatables.length; index++) {
  50655. var animatable = this._animatables[index];
  50656. animatable.restart();
  50657. }
  50658. return this;
  50659. };
  50660. /**
  50661. * Stop all animations
  50662. */
  50663. AnimationGroup.prototype.stop = function () {
  50664. if (!this._isStarted) {
  50665. return this;
  50666. }
  50667. var list = this._animatables.slice();
  50668. for (var index = 0; index < list.length; index++) {
  50669. list[index].stop();
  50670. }
  50671. this._isStarted = false;
  50672. return this;
  50673. };
  50674. /**
  50675. * Set animation weight for all animatables
  50676. * @param weight defines the weight to use
  50677. * @return the animationGroup
  50678. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50679. */
  50680. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50681. for (var index = 0; index < this._animatables.length; index++) {
  50682. var animatable = this._animatables[index];
  50683. animatable.weight = weight;
  50684. }
  50685. return this;
  50686. };
  50687. /**
  50688. * Synchronize and normalize all animatables with a source animatable
  50689. * @param root defines the root animatable to synchronize with
  50690. * @return the animationGroup
  50691. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50692. */
  50693. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50694. for (var index = 0; index < this._animatables.length; index++) {
  50695. var animatable = this._animatables[index];
  50696. animatable.syncWith(root);
  50697. }
  50698. return this;
  50699. };
  50700. /**
  50701. * Goes to a specific frame in this animation group
  50702. * @param frame the frame number to go to
  50703. * @return the animationGroup
  50704. */
  50705. AnimationGroup.prototype.goToFrame = function (frame) {
  50706. if (!this._isStarted) {
  50707. return this;
  50708. }
  50709. for (var index = 0; index < this._animatables.length; index++) {
  50710. var animatable = this._animatables[index];
  50711. animatable.goToFrame(frame);
  50712. }
  50713. return this;
  50714. };
  50715. /**
  50716. * Dispose all associated resources
  50717. */
  50718. AnimationGroup.prototype.dispose = function () {
  50719. this._targetedAnimations = [];
  50720. this._animatables = [];
  50721. var index = this._scene.animationGroups.indexOf(this);
  50722. if (index > -1) {
  50723. this._scene.animationGroups.splice(index, 1);
  50724. }
  50725. };
  50726. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50727. // animatable should be taken out of the array
  50728. var idx = this._animatables.indexOf(animatable);
  50729. if (idx > -1) {
  50730. this._animatables.splice(idx, 1);
  50731. }
  50732. // all animatables were removed? animation group ended!
  50733. if (this._animatables.length === 0) {
  50734. this._isStarted = false;
  50735. this.onAnimationGroupEndObservable.notifyObservers(this);
  50736. }
  50737. };
  50738. return AnimationGroup;
  50739. }());
  50740. BABYLON.AnimationGroup = AnimationGroup;
  50741. })(BABYLON || (BABYLON = {}));
  50742. //# sourceMappingURL=babylon.animationGroup.js.map
  50743. var BABYLON;
  50744. (function (BABYLON) {
  50745. /**
  50746. * Defines a runtime animation
  50747. */
  50748. var RuntimeAnimation = /** @class */ (function () {
  50749. /**
  50750. * Create a new RuntimeAnimation object
  50751. * @param target defines the target of the animation
  50752. * @param animation defines the source animation object
  50753. * @param scene defines the hosting scene
  50754. * @param host defines the initiating Animatable
  50755. */
  50756. function RuntimeAnimation(target, animation, scene, host) {
  50757. var _this = this;
  50758. this._events = new Array();
  50759. /**
  50760. * The current frame of the runtime animation
  50761. */
  50762. this._currentFrame = 0;
  50763. /**
  50764. * The original value of the runtime animation
  50765. */
  50766. this._originalValue = new Array();
  50767. /**
  50768. * The offsets cache of the runtime animation
  50769. */
  50770. this._offsetsCache = {};
  50771. /**
  50772. * The high limits cache of the runtime animation
  50773. */
  50774. this._highLimitsCache = {};
  50775. /**
  50776. * Specifies if the runtime animation has been stopped
  50777. */
  50778. this._stopped = false;
  50779. /**
  50780. * The blending factor of the runtime animation
  50781. */
  50782. this._blendingFactor = 0;
  50783. /**
  50784. * The target path of the runtime animation
  50785. */
  50786. this._targetPath = "";
  50787. /**
  50788. * The weight of the runtime animation
  50789. */
  50790. this._weight = 1.0;
  50791. /**
  50792. * The ratio offset of the runtime animation
  50793. */
  50794. this._ratioOffset = 0;
  50795. /**
  50796. * The previous delay of the runtime animation
  50797. */
  50798. this._previousDelay = 0;
  50799. /**
  50800. * The previous ratio of the runtime animation
  50801. */
  50802. this._previousRatio = 0;
  50803. this._animation = animation;
  50804. this._target = target;
  50805. this._scene = scene;
  50806. this._host = host;
  50807. animation._runtimeAnimations.push(this);
  50808. // Cloning events locally
  50809. var events = animation.getEvents();
  50810. if (events && events.length > 0) {
  50811. events.forEach(function (e) {
  50812. _this._events.push(e._clone());
  50813. });
  50814. }
  50815. }
  50816. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50817. /**
  50818. * Gets the current frame of the runtime animation
  50819. */
  50820. get: function () {
  50821. return this._currentFrame;
  50822. },
  50823. enumerable: true,
  50824. configurable: true
  50825. });
  50826. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50827. /**
  50828. * Gets the weight of the runtime animation
  50829. */
  50830. get: function () {
  50831. return this._weight;
  50832. },
  50833. enumerable: true,
  50834. configurable: true
  50835. });
  50836. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50837. /**
  50838. * Gets the current value of the runtime animation
  50839. */
  50840. get: function () {
  50841. return this._currentValue;
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50847. /**
  50848. * Gets the target path of the runtime animation
  50849. */
  50850. get: function () {
  50851. return this._targetPath;
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50857. /**
  50858. * Gets the actual target of the runtime animation
  50859. */
  50860. get: function () {
  50861. return this._activeTarget;
  50862. },
  50863. enumerable: true,
  50864. configurable: true
  50865. });
  50866. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50867. /**
  50868. * Gets the animation from the runtime animation
  50869. */
  50870. get: function () {
  50871. return this._animation;
  50872. },
  50873. enumerable: true,
  50874. configurable: true
  50875. });
  50876. /**
  50877. * Resets the runtime animation to the beginning
  50878. * @param restoreOriginal defines whether to restore the target property to the original value
  50879. */
  50880. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50881. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50882. if (restoreOriginal) {
  50883. if (this._target instanceof Array) {
  50884. var index = 0;
  50885. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50886. var target = _a[_i];
  50887. if (this._originalValue[index] !== undefined) {
  50888. this._setValue(target, this._originalValue[index], -1);
  50889. }
  50890. index++;
  50891. }
  50892. }
  50893. else {
  50894. if (this._originalValue[0] !== undefined) {
  50895. this._setValue(this._target, this._originalValue[0], -1);
  50896. }
  50897. }
  50898. }
  50899. this._offsetsCache = {};
  50900. this._highLimitsCache = {};
  50901. this._currentFrame = 0;
  50902. this._blendingFactor = 0;
  50903. this._originalValue = new Array();
  50904. // Events
  50905. for (var index = 0; index < this._events.length; index++) {
  50906. this._events[index].isDone = false;
  50907. }
  50908. };
  50909. /**
  50910. * Specifies if the runtime animation is stopped
  50911. * @returns Boolean specifying if the runtime animation is stopped
  50912. */
  50913. RuntimeAnimation.prototype.isStopped = function () {
  50914. return this._stopped;
  50915. };
  50916. /**
  50917. * Disposes of the runtime animation
  50918. */
  50919. RuntimeAnimation.prototype.dispose = function () {
  50920. var index = this._animation.runtimeAnimations.indexOf(this);
  50921. if (index > -1) {
  50922. this._animation.runtimeAnimations.splice(index, 1);
  50923. }
  50924. };
  50925. /**
  50926. * Interpolates the animation from the current frame
  50927. * @param currentFrame The frame to interpolate the animation to
  50928. * @param repeatCount The number of times that the animation should loop
  50929. * @param loopMode The type of looping mode to use
  50930. * @param offsetValue Animation offset value
  50931. * @param highLimitValue The high limit value
  50932. * @returns The interpolated value
  50933. */
  50934. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50935. this._currentFrame = currentFrame;
  50936. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50937. this._workValue = BABYLON.Matrix.Zero();
  50938. }
  50939. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50940. };
  50941. /**
  50942. * Apply the interpolated value to the target
  50943. * @param currentValue defines the value computed by the animation
  50944. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50945. */
  50946. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50947. if (weight === void 0) { weight = 1.0; }
  50948. if (this._target instanceof Array) {
  50949. var index = 0;
  50950. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50951. var target = _a[_i];
  50952. this._setValue(target, currentValue, weight, index);
  50953. index++;
  50954. }
  50955. }
  50956. else {
  50957. this._setValue(this._target, currentValue, weight);
  50958. }
  50959. };
  50960. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50961. if (targetIndex === void 0) { targetIndex = 0; }
  50962. // Set value
  50963. var path;
  50964. var destination;
  50965. var targetPropertyPath = this._animation.targetPropertyPath;
  50966. if (targetPropertyPath.length > 1) {
  50967. var property = target[targetPropertyPath[0]];
  50968. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50969. property = property[targetPropertyPath[index]];
  50970. }
  50971. path = targetPropertyPath[targetPropertyPath.length - 1];
  50972. destination = property;
  50973. }
  50974. else {
  50975. path = targetPropertyPath[0];
  50976. destination = target;
  50977. }
  50978. this._targetPath = path;
  50979. this._activeTarget = destination;
  50980. this._weight = weight;
  50981. if (this._originalValue[targetIndex] === undefined) {
  50982. var originalValue = void 0;
  50983. if (destination.getRestPose && path === "_matrix") { // For bones
  50984. originalValue = destination.getRestPose();
  50985. }
  50986. else {
  50987. originalValue = destination[path];
  50988. }
  50989. if (originalValue && originalValue.clone) {
  50990. this._originalValue[targetIndex] = originalValue.clone();
  50991. }
  50992. else {
  50993. this._originalValue[targetIndex] = originalValue;
  50994. }
  50995. }
  50996. // Blending
  50997. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50998. if (enableBlending && this._blendingFactor <= 1.0) {
  50999. if (!this._originalBlendValue) {
  51000. var originalValue = destination[path];
  51001. if (originalValue.clone) {
  51002. this._originalBlendValue = originalValue.clone();
  51003. }
  51004. else {
  51005. this._originalBlendValue = originalValue;
  51006. }
  51007. }
  51008. if (this._originalBlendValue.m) { // Matrix
  51009. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51010. if (this._currentValue) {
  51011. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51012. }
  51013. else {
  51014. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51015. }
  51016. }
  51017. else {
  51018. if (this._currentValue) {
  51019. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51020. }
  51021. else {
  51022. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51023. }
  51024. }
  51025. }
  51026. else {
  51027. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51028. }
  51029. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51030. this._blendingFactor += blendingSpeed;
  51031. }
  51032. else {
  51033. this._currentValue = currentValue;
  51034. }
  51035. if (weight !== -1.0) {
  51036. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51037. }
  51038. else {
  51039. destination[path] = this._currentValue;
  51040. }
  51041. if (target.markAsDirty) {
  51042. target.markAsDirty(this._animation.targetProperty);
  51043. }
  51044. };
  51045. /**
  51046. * Gets the loop pmode of the runtime animation
  51047. * @returns Loop Mode
  51048. */
  51049. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51050. if (this._target && this._target.animationPropertiesOverride) {
  51051. return this._target.animationPropertiesOverride.loopMode;
  51052. }
  51053. return this._animation.loopMode;
  51054. };
  51055. /**
  51056. * Move the current animation to a given frame
  51057. * @param frame defines the frame to move to
  51058. */
  51059. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51060. var keys = this._animation.getKeys();
  51061. if (frame < keys[0].frame) {
  51062. frame = keys[0].frame;
  51063. }
  51064. else if (frame > keys[keys.length - 1].frame) {
  51065. frame = keys[keys.length - 1].frame;
  51066. }
  51067. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51068. this.setValue(currentValue, -1);
  51069. };
  51070. /**
  51071. * @hidden Internal use only
  51072. */
  51073. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51074. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51075. this._ratioOffset = this._previousRatio - newRatio;
  51076. };
  51077. /**
  51078. * Execute the current animation
  51079. * @param delay defines the delay to add to the current frame
  51080. * @param from defines the lower bound of the animation range
  51081. * @param to defines the upper bound of the animation range
  51082. * @param loop defines if the current animation must loop
  51083. * @param speedRatio defines the current speed ratio
  51084. * @param weight defines the weight of the animation (default is -1 so no weight)
  51085. * @returns a boolean indicating if the animation has ended
  51086. */
  51087. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51088. if (weight === void 0) { weight = -1.0; }
  51089. var targetPropertyPath = this._animation.targetPropertyPath;
  51090. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51091. this._stopped = true;
  51092. return false;
  51093. }
  51094. var keys = this._animation.getKeys();
  51095. // Return immediately if there is only one key frame.
  51096. if (keys.length === 1) {
  51097. this.setValue(keys[0].value, weight);
  51098. return !loop;
  51099. }
  51100. var returnValue = true;
  51101. // Adding a start key at frame 0 if missing
  51102. if (keys[0].frame !== 0) {
  51103. var newKey = { frame: 0, value: keys[0].value };
  51104. keys.splice(0, 0, newKey);
  51105. }
  51106. // Check limits
  51107. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51108. from = keys[0].frame;
  51109. }
  51110. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51111. to = keys[keys.length - 1].frame;
  51112. }
  51113. //to and from cannot be the same key
  51114. if (from === to) {
  51115. if (from > keys[0].frame) {
  51116. from--;
  51117. }
  51118. else if (to < keys[keys.length - 1].frame) {
  51119. to++;
  51120. }
  51121. }
  51122. // Compute ratio
  51123. var range = to - from;
  51124. var offsetValue;
  51125. // ratio represents the frame delta between from and to
  51126. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51127. var highLimitValue = 0;
  51128. this._previousDelay = delay;
  51129. this._previousRatio = ratio;
  51130. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51131. returnValue = false;
  51132. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51133. }
  51134. else {
  51135. // Get max value if required
  51136. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51137. var keyOffset = to.toString() + from.toString();
  51138. if (!this._offsetsCache[keyOffset]) {
  51139. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51140. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51141. switch (this._animation.dataType) {
  51142. // Float
  51143. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51144. this._offsetsCache[keyOffset] = toValue - fromValue;
  51145. break;
  51146. // Quaternion
  51147. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51148. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51149. break;
  51150. // Vector3
  51151. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51152. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51153. // Vector2
  51154. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51155. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51156. // Size
  51157. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51158. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51159. // Color3
  51160. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51161. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51162. default:
  51163. break;
  51164. }
  51165. this._highLimitsCache[keyOffset] = toValue;
  51166. }
  51167. highLimitValue = this._highLimitsCache[keyOffset];
  51168. offsetValue = this._offsetsCache[keyOffset];
  51169. }
  51170. }
  51171. if (offsetValue === undefined) {
  51172. switch (this._animation.dataType) {
  51173. // Float
  51174. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51175. offsetValue = 0;
  51176. break;
  51177. // Quaternion
  51178. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51179. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51180. break;
  51181. // Vector3
  51182. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51183. offsetValue = BABYLON.Vector3.Zero();
  51184. break;
  51185. // Vector2
  51186. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51187. offsetValue = BABYLON.Vector2.Zero();
  51188. break;
  51189. // Size
  51190. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51191. offsetValue = BABYLON.Size.Zero();
  51192. break;
  51193. // Color3
  51194. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51195. offsetValue = BABYLON.Color3.Black();
  51196. }
  51197. }
  51198. // Compute value
  51199. var repeatCount = (ratio / range) >> 0;
  51200. var currentFrame = returnValue ? from + ratio % range : to;
  51201. // Need to normalize?
  51202. if (this._host && this._host.syncRoot) {
  51203. var syncRoot = this._host.syncRoot;
  51204. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51205. currentFrame = from + (to - from) * hostNormalizedFrame;
  51206. }
  51207. // Reset events if looping
  51208. var events = this._events;
  51209. if (range > 0 && this.currentFrame > currentFrame ||
  51210. range < 0 && this.currentFrame < currentFrame) {
  51211. // Need to reset animation events
  51212. for (var index = 0; index < events.length; index++) {
  51213. if (!events[index].onlyOnce) {
  51214. // reset event, the animation is looping
  51215. events[index].isDone = false;
  51216. }
  51217. }
  51218. }
  51219. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51220. // Set value
  51221. this.setValue(currentValue, weight);
  51222. // Check events
  51223. for (var index = 0; index < events.length; index++) {
  51224. // Make sure current frame has passed event frame and that event frame is within the current range
  51225. // Also, handle both forward and reverse animations
  51226. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51227. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51228. var event = events[index];
  51229. if (!event.isDone) {
  51230. // If event should be done only once, remove it.
  51231. if (event.onlyOnce) {
  51232. events.splice(index, 1);
  51233. index--;
  51234. }
  51235. event.isDone = true;
  51236. event.action();
  51237. } // Don't do anything if the event has already be done.
  51238. }
  51239. }
  51240. if (!returnValue) {
  51241. this._stopped = true;
  51242. }
  51243. return returnValue;
  51244. };
  51245. return RuntimeAnimation;
  51246. }());
  51247. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51248. })(BABYLON || (BABYLON = {}));
  51249. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51250. var BABYLON;
  51251. (function (BABYLON) {
  51252. var Animatable = /** @class */ (function () {
  51253. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51254. if (fromFrame === void 0) { fromFrame = 0; }
  51255. if (toFrame === void 0) { toFrame = 100; }
  51256. if (loopAnimation === void 0) { loopAnimation = false; }
  51257. if (speedRatio === void 0) { speedRatio = 1.0; }
  51258. this.target = target;
  51259. this.fromFrame = fromFrame;
  51260. this.toFrame = toFrame;
  51261. this.loopAnimation = loopAnimation;
  51262. this.onAnimationEnd = onAnimationEnd;
  51263. this._localDelayOffset = null;
  51264. this._pausedDelay = null;
  51265. this._runtimeAnimations = new Array();
  51266. this._paused = false;
  51267. this._speedRatio = 1;
  51268. this._weight = -1.0;
  51269. this.animationStarted = false;
  51270. /**
  51271. * Observer raised when the animation ends
  51272. */
  51273. this.onAnimationEndObservable = new BABYLON.Observable();
  51274. this._scene = scene;
  51275. if (animations) {
  51276. this.appendAnimations(target, animations);
  51277. }
  51278. this._speedRatio = speedRatio;
  51279. scene._activeAnimatables.push(this);
  51280. }
  51281. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51282. /**
  51283. * Gets the root Animatable used to synchronize and normalize animations
  51284. */
  51285. get: function () {
  51286. return this._syncRoot;
  51287. },
  51288. enumerable: true,
  51289. configurable: true
  51290. });
  51291. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51292. /**
  51293. * Gets the current frame of the first RuntimeAnimation
  51294. * Used to synchronize Animatables
  51295. */
  51296. get: function () {
  51297. if (this._runtimeAnimations.length === 0) {
  51298. return 0;
  51299. }
  51300. return this._runtimeAnimations[0].currentFrame;
  51301. },
  51302. enumerable: true,
  51303. configurable: true
  51304. });
  51305. Object.defineProperty(Animatable.prototype, "weight", {
  51306. /**
  51307. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51308. */
  51309. get: function () {
  51310. return this._weight;
  51311. },
  51312. set: function (value) {
  51313. if (value === -1) { // -1 is ok and means no weight
  51314. this._weight = -1;
  51315. return;
  51316. }
  51317. // Else weight must be in [0, 1] range
  51318. this._weight = Math.min(Math.max(value, 0), 1.0);
  51319. },
  51320. enumerable: true,
  51321. configurable: true
  51322. });
  51323. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51324. /**
  51325. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51326. */
  51327. get: function () {
  51328. return this._speedRatio;
  51329. },
  51330. set: function (value) {
  51331. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51332. var animation = this._runtimeAnimations[index];
  51333. animation._prepareForSpeedRatioChange(value);
  51334. }
  51335. this._speedRatio = value;
  51336. },
  51337. enumerable: true,
  51338. configurable: true
  51339. });
  51340. // Methods
  51341. /**
  51342. * Synchronize and normalize current Animatable with a source Animatable
  51343. * This is useful when using animation weights and when animations are not of the same length
  51344. * @param root defines the root Animatable to synchronize with
  51345. * @returns the current Animatable
  51346. */
  51347. Animatable.prototype.syncWith = function (root) {
  51348. this._syncRoot = root;
  51349. if (root) {
  51350. // Make sure this animatable will animate after the root
  51351. var index = this._scene._activeAnimatables.indexOf(this);
  51352. if (index > -1) {
  51353. this._scene._activeAnimatables.splice(index, 1);
  51354. this._scene._activeAnimatables.push(this);
  51355. }
  51356. }
  51357. return this;
  51358. };
  51359. Animatable.prototype.getAnimations = function () {
  51360. return this._runtimeAnimations;
  51361. };
  51362. Animatable.prototype.appendAnimations = function (target, animations) {
  51363. for (var index = 0; index < animations.length; index++) {
  51364. var animation = animations[index];
  51365. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51366. }
  51367. };
  51368. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51369. var runtimeAnimations = this._runtimeAnimations;
  51370. for (var index = 0; index < runtimeAnimations.length; index++) {
  51371. if (runtimeAnimations[index].animation.targetProperty === property) {
  51372. return runtimeAnimations[index].animation;
  51373. }
  51374. }
  51375. return null;
  51376. };
  51377. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51378. var runtimeAnimations = this._runtimeAnimations;
  51379. for (var index = 0; index < runtimeAnimations.length; index++) {
  51380. if (runtimeAnimations[index].animation.targetProperty === property) {
  51381. return runtimeAnimations[index];
  51382. }
  51383. }
  51384. return null;
  51385. };
  51386. Animatable.prototype.reset = function () {
  51387. var runtimeAnimations = this._runtimeAnimations;
  51388. for (var index = 0; index < runtimeAnimations.length; index++) {
  51389. runtimeAnimations[index].reset(true);
  51390. }
  51391. this._localDelayOffset = null;
  51392. this._pausedDelay = null;
  51393. };
  51394. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51395. var runtimeAnimations = this._runtimeAnimations;
  51396. for (var index = 0; index < runtimeAnimations.length; index++) {
  51397. runtimeAnimations[index].animation.enableBlending = true;
  51398. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51399. }
  51400. };
  51401. Animatable.prototype.disableBlending = function () {
  51402. var runtimeAnimations = this._runtimeAnimations;
  51403. for (var index = 0; index < runtimeAnimations.length; index++) {
  51404. runtimeAnimations[index].animation.enableBlending = false;
  51405. }
  51406. };
  51407. Animatable.prototype.goToFrame = function (frame) {
  51408. var runtimeAnimations = this._runtimeAnimations;
  51409. if (runtimeAnimations[0]) {
  51410. var fps = runtimeAnimations[0].animation.framePerSecond;
  51411. var currentFrame = runtimeAnimations[0].currentFrame;
  51412. var adjustTime = frame - currentFrame;
  51413. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51414. if (this._localDelayOffset === null) {
  51415. this._localDelayOffset = 0;
  51416. }
  51417. this._localDelayOffset -= delay;
  51418. }
  51419. for (var index = 0; index < runtimeAnimations.length; index++) {
  51420. runtimeAnimations[index].goToFrame(frame);
  51421. }
  51422. };
  51423. Animatable.prototype.pause = function () {
  51424. if (this._paused) {
  51425. return;
  51426. }
  51427. this._paused = true;
  51428. };
  51429. Animatable.prototype.restart = function () {
  51430. this._paused = false;
  51431. };
  51432. Animatable.prototype._raiseOnAnimationEnd = function () {
  51433. if (this.onAnimationEnd) {
  51434. this.onAnimationEnd();
  51435. }
  51436. this.onAnimationEndObservable.notifyObservers(this);
  51437. };
  51438. Animatable.prototype.stop = function (animationName) {
  51439. if (animationName) {
  51440. var idx = this._scene._activeAnimatables.indexOf(this);
  51441. if (idx > -1) {
  51442. var runtimeAnimations = this._runtimeAnimations;
  51443. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51444. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51445. continue;
  51446. }
  51447. runtimeAnimations[index].dispose();
  51448. runtimeAnimations.splice(index, 1);
  51449. }
  51450. if (runtimeAnimations.length == 0) {
  51451. this._scene._activeAnimatables.splice(idx, 1);
  51452. this._raiseOnAnimationEnd();
  51453. }
  51454. }
  51455. }
  51456. else {
  51457. var index = this._scene._activeAnimatables.indexOf(this);
  51458. if (index > -1) {
  51459. this._scene._activeAnimatables.splice(index, 1);
  51460. var runtimeAnimations = this._runtimeAnimations;
  51461. for (var index = 0; index < runtimeAnimations.length; index++) {
  51462. runtimeAnimations[index].dispose();
  51463. }
  51464. this._raiseOnAnimationEnd();
  51465. }
  51466. }
  51467. };
  51468. /**
  51469. * Wait asynchronously for the animation to end
  51470. * @returns a promise which will be fullfilled when the animation ends
  51471. */
  51472. Animatable.prototype.waitAsync = function () {
  51473. var _this = this;
  51474. return new Promise(function (resolve, reject) {
  51475. _this.onAnimationEndObservable.add(function () {
  51476. resolve(_this);
  51477. }, undefined, undefined, _this, true);
  51478. });
  51479. };
  51480. /** @hidden */
  51481. Animatable.prototype._animate = function (delay) {
  51482. if (this._paused) {
  51483. this.animationStarted = false;
  51484. if (this._pausedDelay === null) {
  51485. this._pausedDelay = delay;
  51486. }
  51487. return true;
  51488. }
  51489. if (this._localDelayOffset === null) {
  51490. this._localDelayOffset = delay;
  51491. this._pausedDelay = null;
  51492. }
  51493. else if (this._pausedDelay !== null) {
  51494. this._localDelayOffset += delay - this._pausedDelay;
  51495. this._pausedDelay = null;
  51496. }
  51497. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51498. return true;
  51499. }
  51500. // Animating
  51501. var running = false;
  51502. var runtimeAnimations = this._runtimeAnimations;
  51503. var index;
  51504. for (index = 0; index < runtimeAnimations.length; index++) {
  51505. var animation = runtimeAnimations[index];
  51506. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51507. running = running || isRunning;
  51508. }
  51509. this.animationStarted = running;
  51510. if (!running) {
  51511. // Remove from active animatables
  51512. index = this._scene._activeAnimatables.indexOf(this);
  51513. this._scene._activeAnimatables.splice(index, 1);
  51514. // Dispose all runtime animations
  51515. for (index = 0; index < runtimeAnimations.length; index++) {
  51516. runtimeAnimations[index].dispose();
  51517. }
  51518. this._raiseOnAnimationEnd();
  51519. this.onAnimationEnd = null;
  51520. this.onAnimationEndObservable.clear();
  51521. }
  51522. return running;
  51523. };
  51524. return Animatable;
  51525. }());
  51526. BABYLON.Animatable = Animatable;
  51527. })(BABYLON || (BABYLON = {}));
  51528. //# sourceMappingURL=babylon.animatable.js.map
  51529. var BABYLON;
  51530. (function (BABYLON) {
  51531. var EasingFunction = /** @class */ (function () {
  51532. function EasingFunction() {
  51533. // Properties
  51534. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51535. }
  51536. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51537. get: function () {
  51538. return EasingFunction._EASINGMODE_EASEIN;
  51539. },
  51540. enumerable: true,
  51541. configurable: true
  51542. });
  51543. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51544. get: function () {
  51545. return EasingFunction._EASINGMODE_EASEOUT;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51551. get: function () {
  51552. return EasingFunction._EASINGMODE_EASEINOUT;
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51558. var n = Math.min(Math.max(easingMode, 0), 2);
  51559. this._easingMode = n;
  51560. };
  51561. EasingFunction.prototype.getEasingMode = function () {
  51562. return this._easingMode;
  51563. };
  51564. EasingFunction.prototype.easeInCore = function (gradient) {
  51565. throw new Error('You must implement this method');
  51566. };
  51567. EasingFunction.prototype.ease = function (gradient) {
  51568. switch (this._easingMode) {
  51569. case EasingFunction.EASINGMODE_EASEIN:
  51570. return this.easeInCore(gradient);
  51571. case EasingFunction.EASINGMODE_EASEOUT:
  51572. return (1 - this.easeInCore(1 - gradient));
  51573. }
  51574. if (gradient >= 0.5) {
  51575. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51576. }
  51577. return (this.easeInCore(gradient * 2) * 0.5);
  51578. };
  51579. //Statics
  51580. EasingFunction._EASINGMODE_EASEIN = 0;
  51581. EasingFunction._EASINGMODE_EASEOUT = 1;
  51582. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51583. return EasingFunction;
  51584. }());
  51585. BABYLON.EasingFunction = EasingFunction;
  51586. var CircleEase = /** @class */ (function (_super) {
  51587. __extends(CircleEase, _super);
  51588. function CircleEase() {
  51589. return _super !== null && _super.apply(this, arguments) || this;
  51590. }
  51591. CircleEase.prototype.easeInCore = function (gradient) {
  51592. gradient = Math.max(0, Math.min(1, gradient));
  51593. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51594. };
  51595. return CircleEase;
  51596. }(EasingFunction));
  51597. BABYLON.CircleEase = CircleEase;
  51598. var BackEase = /** @class */ (function (_super) {
  51599. __extends(BackEase, _super);
  51600. function BackEase(amplitude) {
  51601. if (amplitude === void 0) { amplitude = 1; }
  51602. var _this = _super.call(this) || this;
  51603. _this.amplitude = amplitude;
  51604. return _this;
  51605. }
  51606. BackEase.prototype.easeInCore = function (gradient) {
  51607. var num = Math.max(0, this.amplitude);
  51608. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51609. };
  51610. return BackEase;
  51611. }(EasingFunction));
  51612. BABYLON.BackEase = BackEase;
  51613. var BounceEase = /** @class */ (function (_super) {
  51614. __extends(BounceEase, _super);
  51615. function BounceEase(bounces, bounciness) {
  51616. if (bounces === void 0) { bounces = 3; }
  51617. if (bounciness === void 0) { bounciness = 2; }
  51618. var _this = _super.call(this) || this;
  51619. _this.bounces = bounces;
  51620. _this.bounciness = bounciness;
  51621. return _this;
  51622. }
  51623. BounceEase.prototype.easeInCore = function (gradient) {
  51624. var y = Math.max(0.0, this.bounces);
  51625. var bounciness = this.bounciness;
  51626. if (bounciness <= 1.0) {
  51627. bounciness = 1.001;
  51628. }
  51629. var num9 = Math.pow(bounciness, y);
  51630. var num5 = 1.0 - bounciness;
  51631. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51632. var num15 = gradient * num4;
  51633. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51634. var num3 = Math.floor(num65);
  51635. var num13 = num3 + 1.0;
  51636. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51637. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51638. var num7 = (num8 + num12) * 0.5;
  51639. var num6 = gradient - num7;
  51640. var num2 = num7 - num8;
  51641. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51642. };
  51643. return BounceEase;
  51644. }(EasingFunction));
  51645. BABYLON.BounceEase = BounceEase;
  51646. var CubicEase = /** @class */ (function (_super) {
  51647. __extends(CubicEase, _super);
  51648. function CubicEase() {
  51649. return _super !== null && _super.apply(this, arguments) || this;
  51650. }
  51651. CubicEase.prototype.easeInCore = function (gradient) {
  51652. return (gradient * gradient * gradient);
  51653. };
  51654. return CubicEase;
  51655. }(EasingFunction));
  51656. BABYLON.CubicEase = CubicEase;
  51657. var ElasticEase = /** @class */ (function (_super) {
  51658. __extends(ElasticEase, _super);
  51659. function ElasticEase(oscillations, springiness) {
  51660. if (oscillations === void 0) { oscillations = 3; }
  51661. if (springiness === void 0) { springiness = 3; }
  51662. var _this = _super.call(this) || this;
  51663. _this.oscillations = oscillations;
  51664. _this.springiness = springiness;
  51665. return _this;
  51666. }
  51667. ElasticEase.prototype.easeInCore = function (gradient) {
  51668. var num2;
  51669. var num3 = Math.max(0.0, this.oscillations);
  51670. var num = Math.max(0.0, this.springiness);
  51671. if (num == 0) {
  51672. num2 = gradient;
  51673. }
  51674. else {
  51675. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51676. }
  51677. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51678. };
  51679. return ElasticEase;
  51680. }(EasingFunction));
  51681. BABYLON.ElasticEase = ElasticEase;
  51682. var ExponentialEase = /** @class */ (function (_super) {
  51683. __extends(ExponentialEase, _super);
  51684. function ExponentialEase(exponent) {
  51685. if (exponent === void 0) { exponent = 2; }
  51686. var _this = _super.call(this) || this;
  51687. _this.exponent = exponent;
  51688. return _this;
  51689. }
  51690. ExponentialEase.prototype.easeInCore = function (gradient) {
  51691. if (this.exponent <= 0) {
  51692. return gradient;
  51693. }
  51694. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51695. };
  51696. return ExponentialEase;
  51697. }(EasingFunction));
  51698. BABYLON.ExponentialEase = ExponentialEase;
  51699. var PowerEase = /** @class */ (function (_super) {
  51700. __extends(PowerEase, _super);
  51701. function PowerEase(power) {
  51702. if (power === void 0) { power = 2; }
  51703. var _this = _super.call(this) || this;
  51704. _this.power = power;
  51705. return _this;
  51706. }
  51707. PowerEase.prototype.easeInCore = function (gradient) {
  51708. var y = Math.max(0.0, this.power);
  51709. return Math.pow(gradient, y);
  51710. };
  51711. return PowerEase;
  51712. }(EasingFunction));
  51713. BABYLON.PowerEase = PowerEase;
  51714. var QuadraticEase = /** @class */ (function (_super) {
  51715. __extends(QuadraticEase, _super);
  51716. function QuadraticEase() {
  51717. return _super !== null && _super.apply(this, arguments) || this;
  51718. }
  51719. QuadraticEase.prototype.easeInCore = function (gradient) {
  51720. return (gradient * gradient);
  51721. };
  51722. return QuadraticEase;
  51723. }(EasingFunction));
  51724. BABYLON.QuadraticEase = QuadraticEase;
  51725. var QuarticEase = /** @class */ (function (_super) {
  51726. __extends(QuarticEase, _super);
  51727. function QuarticEase() {
  51728. return _super !== null && _super.apply(this, arguments) || this;
  51729. }
  51730. QuarticEase.prototype.easeInCore = function (gradient) {
  51731. return (gradient * gradient * gradient * gradient);
  51732. };
  51733. return QuarticEase;
  51734. }(EasingFunction));
  51735. BABYLON.QuarticEase = QuarticEase;
  51736. var QuinticEase = /** @class */ (function (_super) {
  51737. __extends(QuinticEase, _super);
  51738. function QuinticEase() {
  51739. return _super !== null && _super.apply(this, arguments) || this;
  51740. }
  51741. QuinticEase.prototype.easeInCore = function (gradient) {
  51742. return (gradient * gradient * gradient * gradient * gradient);
  51743. };
  51744. return QuinticEase;
  51745. }(EasingFunction));
  51746. BABYLON.QuinticEase = QuinticEase;
  51747. var SineEase = /** @class */ (function (_super) {
  51748. __extends(SineEase, _super);
  51749. function SineEase() {
  51750. return _super !== null && _super.apply(this, arguments) || this;
  51751. }
  51752. SineEase.prototype.easeInCore = function (gradient) {
  51753. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51754. };
  51755. return SineEase;
  51756. }(EasingFunction));
  51757. BABYLON.SineEase = SineEase;
  51758. var BezierCurveEase = /** @class */ (function (_super) {
  51759. __extends(BezierCurveEase, _super);
  51760. function BezierCurveEase(x1, y1, x2, y2) {
  51761. if (x1 === void 0) { x1 = 0; }
  51762. if (y1 === void 0) { y1 = 0; }
  51763. if (x2 === void 0) { x2 = 1; }
  51764. if (y2 === void 0) { y2 = 1; }
  51765. var _this = _super.call(this) || this;
  51766. _this.x1 = x1;
  51767. _this.y1 = y1;
  51768. _this.x2 = x2;
  51769. _this.y2 = y2;
  51770. return _this;
  51771. }
  51772. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51773. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51774. };
  51775. return BezierCurveEase;
  51776. }(EasingFunction));
  51777. BABYLON.BezierCurveEase = BezierCurveEase;
  51778. })(BABYLON || (BABYLON = {}));
  51779. //# sourceMappingURL=babylon.easing.js.map
  51780. var BABYLON;
  51781. (function (BABYLON) {
  51782. /**
  51783. * A Condition applied to an Action
  51784. */
  51785. var Condition = /** @class */ (function () {
  51786. /**
  51787. * Creates a new Condition
  51788. * @param actionManager the manager of the action the condition is applied to
  51789. */
  51790. function Condition(actionManager) {
  51791. this._actionManager = actionManager;
  51792. }
  51793. /**
  51794. * Check if the current condition is valid
  51795. * @returns a boolean
  51796. */
  51797. Condition.prototype.isValid = function () {
  51798. return true;
  51799. };
  51800. /**
  51801. * Internal only
  51802. * @hidden
  51803. */
  51804. Condition.prototype._getProperty = function (propertyPath) {
  51805. return this._actionManager._getProperty(propertyPath);
  51806. };
  51807. /**
  51808. * Internal only
  51809. * @hidden
  51810. */
  51811. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51812. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51813. };
  51814. /**
  51815. * Serialize placeholder for child classes
  51816. * @returns the serialized object
  51817. */
  51818. Condition.prototype.serialize = function () {
  51819. };
  51820. /**
  51821. * Internal only
  51822. * @hidden
  51823. */
  51824. Condition.prototype._serialize = function (serializedCondition) {
  51825. return {
  51826. type: 2,
  51827. children: [],
  51828. name: serializedCondition.name,
  51829. properties: serializedCondition.properties
  51830. };
  51831. };
  51832. return Condition;
  51833. }());
  51834. BABYLON.Condition = Condition;
  51835. /**
  51836. * Defines specific conditional operators as extensions of Condition
  51837. */
  51838. var ValueCondition = /** @class */ (function (_super) {
  51839. __extends(ValueCondition, _super);
  51840. /**
  51841. * Creates a new ValueCondition
  51842. * @param actionManager manager for the action the condition applies to
  51843. * @param target for the action
  51844. * @param propertyPath path to specify the property of the target the conditional operator uses
  51845. * @param value the value compared by the conditional operator against the current value of the property
  51846. * @param operator the conditional operator, default ValueCondition.IsEqual
  51847. */
  51848. function ValueCondition(actionManager, target,
  51849. /** path to specify the property of the target the conditional operator uses */
  51850. propertyPath,
  51851. /** the value compared by the conditional operator against the current value of the property */
  51852. value,
  51853. /** the conditional operator, default ValueCondition.IsEqual */
  51854. operator) {
  51855. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51856. var _this = _super.call(this, actionManager) || this;
  51857. _this.propertyPath = propertyPath;
  51858. _this.value = value;
  51859. _this.operator = operator;
  51860. _this._target = target;
  51861. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51862. _this._property = _this._getProperty(_this.propertyPath);
  51863. return _this;
  51864. }
  51865. Object.defineProperty(ValueCondition, "IsEqual", {
  51866. /**
  51867. * returns the number for IsEqual
  51868. */
  51869. get: function () {
  51870. return ValueCondition._IsEqual;
  51871. },
  51872. enumerable: true,
  51873. configurable: true
  51874. });
  51875. Object.defineProperty(ValueCondition, "IsDifferent", {
  51876. /**
  51877. * Returns the number for IsDifferent
  51878. */
  51879. get: function () {
  51880. return ValueCondition._IsDifferent;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. Object.defineProperty(ValueCondition, "IsGreater", {
  51886. /**
  51887. * Returns the number for IsGreater
  51888. */
  51889. get: function () {
  51890. return ValueCondition._IsGreater;
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. Object.defineProperty(ValueCondition, "IsLesser", {
  51896. /**
  51897. * Returns the number for IsLesser
  51898. */
  51899. get: function () {
  51900. return ValueCondition._IsLesser;
  51901. },
  51902. enumerable: true,
  51903. configurable: true
  51904. });
  51905. /**
  51906. * Compares the given value with the property value for the specified conditional operator
  51907. * @returns the result of the comparison
  51908. */
  51909. ValueCondition.prototype.isValid = function () {
  51910. switch (this.operator) {
  51911. case ValueCondition.IsGreater:
  51912. return this._effectiveTarget[this._property] > this.value;
  51913. case ValueCondition.IsLesser:
  51914. return this._effectiveTarget[this._property] < this.value;
  51915. case ValueCondition.IsEqual:
  51916. case ValueCondition.IsDifferent:
  51917. var check;
  51918. if (this.value.equals) {
  51919. check = this.value.equals(this._effectiveTarget[this._property]);
  51920. }
  51921. else {
  51922. check = this.value === this._effectiveTarget[this._property];
  51923. }
  51924. return this.operator === ValueCondition.IsEqual ? check : !check;
  51925. }
  51926. return false;
  51927. };
  51928. /**
  51929. * Serialize the ValueCondition into a JSON compatible object
  51930. * @returns serialization object
  51931. */
  51932. ValueCondition.prototype.serialize = function () {
  51933. return this._serialize({
  51934. name: "ValueCondition",
  51935. properties: [
  51936. BABYLON.Action._GetTargetProperty(this._target),
  51937. { name: "propertyPath", value: this.propertyPath },
  51938. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51939. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51940. ]
  51941. });
  51942. };
  51943. /**
  51944. * Gets the name of the conditional operator for the ValueCondition
  51945. * @param operator the conditional operator
  51946. * @returns the name
  51947. */
  51948. ValueCondition.GetOperatorName = function (operator) {
  51949. switch (operator) {
  51950. case ValueCondition._IsEqual: return "IsEqual";
  51951. case ValueCondition._IsDifferent: return "IsDifferent";
  51952. case ValueCondition._IsGreater: return "IsGreater";
  51953. case ValueCondition._IsLesser: return "IsLesser";
  51954. default: return "";
  51955. }
  51956. };
  51957. /**
  51958. * Internal only
  51959. * @hidden
  51960. */
  51961. ValueCondition._IsEqual = 0;
  51962. /**
  51963. * Internal only
  51964. * @hidden
  51965. */
  51966. ValueCondition._IsDifferent = 1;
  51967. /**
  51968. * Internal only
  51969. * @hidden
  51970. */
  51971. ValueCondition._IsGreater = 2;
  51972. /**
  51973. * Internal only
  51974. * @hidden
  51975. */
  51976. ValueCondition._IsLesser = 3;
  51977. return ValueCondition;
  51978. }(Condition));
  51979. BABYLON.ValueCondition = ValueCondition;
  51980. /**
  51981. * Defines a predicate condition as an extension of Condition
  51982. */
  51983. var PredicateCondition = /** @class */ (function (_super) {
  51984. __extends(PredicateCondition, _super);
  51985. /**
  51986. * Creates a new PredicateCondition
  51987. * @param actionManager manager for the action the condition applies to
  51988. * @param predicate defines the predicate function used to validate the condition
  51989. */
  51990. function PredicateCondition(actionManager,
  51991. /** defines the predicate function used to validate the condition */
  51992. predicate) {
  51993. var _this = _super.call(this, actionManager) || this;
  51994. _this.predicate = predicate;
  51995. return _this;
  51996. }
  51997. /**
  51998. * @returns the validity of the predicate condition
  51999. */
  52000. PredicateCondition.prototype.isValid = function () {
  52001. return this.predicate();
  52002. };
  52003. return PredicateCondition;
  52004. }(Condition));
  52005. BABYLON.PredicateCondition = PredicateCondition;
  52006. /**
  52007. * Defines a state condition as an extension of Condition
  52008. */
  52009. var StateCondition = /** @class */ (function (_super) {
  52010. __extends(StateCondition, _super);
  52011. /**
  52012. * Creates a new StateCondition
  52013. * @param actionManager manager for the action the condition applies to
  52014. * @param target of the condition
  52015. * @param value to compare with target state
  52016. */
  52017. function StateCondition(actionManager, target, value) {
  52018. var _this = _super.call(this, actionManager) || this;
  52019. _this.value = value;
  52020. _this._target = target;
  52021. return _this;
  52022. }
  52023. /**
  52024. * @returns the validity of the state
  52025. */
  52026. StateCondition.prototype.isValid = function () {
  52027. return this._target.state === this.value;
  52028. };
  52029. /**
  52030. * Serialize the StateCondition into a JSON compatible object
  52031. * @returns serialization object
  52032. */
  52033. StateCondition.prototype.serialize = function () {
  52034. return this._serialize({
  52035. name: "StateCondition",
  52036. properties: [
  52037. BABYLON.Action._GetTargetProperty(this._target),
  52038. { name: "value", value: this.value }
  52039. ]
  52040. });
  52041. };
  52042. return StateCondition;
  52043. }(Condition));
  52044. BABYLON.StateCondition = StateCondition;
  52045. })(BABYLON || (BABYLON = {}));
  52046. //# sourceMappingURL=babylon.condition.js.map
  52047. var BABYLON;
  52048. (function (BABYLON) {
  52049. /**
  52050. * The action to be carried out following a trigger
  52051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52052. */
  52053. var Action = /** @class */ (function () {
  52054. /**
  52055. * Creates a new Action
  52056. * @param triggerOptions the trigger, with or without parameters, for the action
  52057. * @param condition an optional determinant of action
  52058. */
  52059. function Action(
  52060. /** the trigger, with or without parameters, for the action */
  52061. triggerOptions, condition) {
  52062. this.triggerOptions = triggerOptions;
  52063. /**
  52064. * An event triggered prior to action being executed.
  52065. */
  52066. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52067. if (triggerOptions.parameter) {
  52068. this.trigger = triggerOptions.trigger;
  52069. this._triggerParameter = triggerOptions.parameter;
  52070. }
  52071. else {
  52072. this.trigger = triggerOptions;
  52073. }
  52074. this._nextActiveAction = this;
  52075. this._condition = condition;
  52076. }
  52077. /**
  52078. * Internal only
  52079. * @hidden
  52080. */
  52081. Action.prototype._prepare = function () {
  52082. };
  52083. /**
  52084. * Gets the trigger parameters
  52085. * @returns the trigger parameters
  52086. */
  52087. Action.prototype.getTriggerParameter = function () {
  52088. return this._triggerParameter;
  52089. };
  52090. /**
  52091. * Internal only - executes current action event
  52092. * @hidden
  52093. */
  52094. Action.prototype._executeCurrent = function (evt) {
  52095. if (this._nextActiveAction._condition) {
  52096. var condition = this._nextActiveAction._condition;
  52097. var currentRenderId = this._actionManager.getScene().getRenderId();
  52098. // We cache the current evaluation for the current frame
  52099. if (condition._evaluationId === currentRenderId) {
  52100. if (!condition._currentResult) {
  52101. return;
  52102. }
  52103. }
  52104. else {
  52105. condition._evaluationId = currentRenderId;
  52106. if (!condition.isValid()) {
  52107. condition._currentResult = false;
  52108. return;
  52109. }
  52110. condition._currentResult = true;
  52111. }
  52112. }
  52113. this.onBeforeExecuteObservable.notifyObservers(this);
  52114. this._nextActiveAction.execute(evt);
  52115. this.skipToNextActiveAction();
  52116. };
  52117. /**
  52118. * Execute placeholder for child classes
  52119. * @param evt optional action event
  52120. */
  52121. Action.prototype.execute = function (evt) {
  52122. };
  52123. /**
  52124. * Skips to next active action
  52125. */
  52126. Action.prototype.skipToNextActiveAction = function () {
  52127. if (this._nextActiveAction._child) {
  52128. if (!this._nextActiveAction._child._actionManager) {
  52129. this._nextActiveAction._child._actionManager = this._actionManager;
  52130. }
  52131. this._nextActiveAction = this._nextActiveAction._child;
  52132. }
  52133. else {
  52134. this._nextActiveAction = this;
  52135. }
  52136. };
  52137. /**
  52138. * Adds action to chain of actions, may be a DoNothingAction
  52139. * @param action defines the next action to execute
  52140. * @returns The action passed in
  52141. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52142. */
  52143. Action.prototype.then = function (action) {
  52144. this._child = action;
  52145. action._actionManager = this._actionManager;
  52146. action._prepare();
  52147. return action;
  52148. };
  52149. /**
  52150. * Internal only
  52151. * @hidden
  52152. */
  52153. Action.prototype._getProperty = function (propertyPath) {
  52154. return this._actionManager._getProperty(propertyPath);
  52155. };
  52156. /**
  52157. * Internal only
  52158. * @hidden
  52159. */
  52160. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52161. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52162. };
  52163. /**
  52164. * Serialize placeholder for child classes
  52165. * @param parent of child
  52166. * @returns the serialized object
  52167. */
  52168. Action.prototype.serialize = function (parent) {
  52169. };
  52170. /**
  52171. * Internal only called by serialize
  52172. * @hidden
  52173. */
  52174. Action.prototype._serialize = function (serializedAction, parent) {
  52175. var serializationObject = {
  52176. type: 1,
  52177. children: [],
  52178. name: serializedAction.name,
  52179. properties: serializedAction.properties || []
  52180. };
  52181. // Serialize child
  52182. if (this._child) {
  52183. this._child.serialize(serializationObject);
  52184. }
  52185. // Check if "this" has a condition
  52186. if (this._condition) {
  52187. var serializedCondition = this._condition.serialize();
  52188. serializedCondition.children.push(serializationObject);
  52189. if (parent) {
  52190. parent.children.push(serializedCondition);
  52191. }
  52192. return serializedCondition;
  52193. }
  52194. if (parent) {
  52195. parent.children.push(serializationObject);
  52196. }
  52197. return serializationObject;
  52198. };
  52199. /**
  52200. * Internal only
  52201. * @hidden
  52202. */
  52203. Action._SerializeValueAsString = function (value) {
  52204. if (typeof value === "number") {
  52205. return value.toString();
  52206. }
  52207. if (typeof value === "boolean") {
  52208. return value ? "true" : "false";
  52209. }
  52210. if (value instanceof BABYLON.Vector2) {
  52211. return value.x + ", " + value.y;
  52212. }
  52213. if (value instanceof BABYLON.Vector3) {
  52214. return value.x + ", " + value.y + ", " + value.z;
  52215. }
  52216. if (value instanceof BABYLON.Color3) {
  52217. return value.r + ", " + value.g + ", " + value.b;
  52218. }
  52219. if (value instanceof BABYLON.Color4) {
  52220. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52221. }
  52222. return value; // string
  52223. };
  52224. /**
  52225. * Internal only
  52226. * @hidden
  52227. */
  52228. Action._GetTargetProperty = function (target) {
  52229. return {
  52230. name: "target",
  52231. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52232. : target instanceof BABYLON.Light ? "LightProperties"
  52233. : target instanceof BABYLON.Camera ? "CameraProperties"
  52234. : "SceneProperties",
  52235. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52236. };
  52237. };
  52238. return Action;
  52239. }());
  52240. BABYLON.Action = Action;
  52241. })(BABYLON || (BABYLON = {}));
  52242. //# sourceMappingURL=babylon.action.js.map
  52243. var BABYLON;
  52244. (function (BABYLON) {
  52245. /**
  52246. * ActionEvent is the event being sent when an action is triggered.
  52247. */
  52248. var ActionEvent = /** @class */ (function () {
  52249. /**
  52250. * Creates a new ActionEvent
  52251. * @param source The mesh or sprite that triggered the action
  52252. * @param pointerX The X mouse cursor position at the time of the event
  52253. * @param pointerY The Y mouse cursor position at the time of the event
  52254. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52255. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52256. * @param additionalData additional data for the event
  52257. */
  52258. function ActionEvent(
  52259. /** The mesh or sprite that triggered the action */
  52260. source,
  52261. /** The X mouse cursor position at the time of the event */
  52262. pointerX,
  52263. /** The Y mouse cursor position at the time of the event */
  52264. pointerY,
  52265. /** The mesh that is currently pointed at (can be null) */
  52266. meshUnderPointer,
  52267. /** the original (browser) event that triggered the ActionEvent */
  52268. sourceEvent,
  52269. /** additional data for the event */
  52270. additionalData) {
  52271. this.source = source;
  52272. this.pointerX = pointerX;
  52273. this.pointerY = pointerY;
  52274. this.meshUnderPointer = meshUnderPointer;
  52275. this.sourceEvent = sourceEvent;
  52276. this.additionalData = additionalData;
  52277. }
  52278. /**
  52279. * Helper function to auto-create an ActionEvent from a source mesh.
  52280. * @param source The source mesh that triggered the event
  52281. * @param evt The original (browser) event
  52282. * @param additionalData additional data for the event
  52283. * @returns the new ActionEvent
  52284. */
  52285. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52286. var scene = source.getScene();
  52287. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52288. };
  52289. /**
  52290. * Helper function to auto-create an ActionEvent from a source sprite
  52291. * @param source The source sprite that triggered the event
  52292. * @param scene Scene associated with the sprite
  52293. * @param evt The original (browser) event
  52294. * @param additionalData additional data for the event
  52295. * @returns the new ActionEvent
  52296. */
  52297. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52298. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52299. };
  52300. /**
  52301. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52302. * @param scene the scene where the event occurred
  52303. * @param evt The original (browser) event
  52304. * @returns the new ActionEvent
  52305. */
  52306. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52307. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52308. };
  52309. /**
  52310. * Helper function to auto-create an ActionEvent from a primitive
  52311. * @param prim defines the target primitive
  52312. * @param pointerPos defines the pointer position
  52313. * @param evt The original (browser) event
  52314. * @param additionalData additional data for the event
  52315. * @returns the new ActionEvent
  52316. */
  52317. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52318. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52319. };
  52320. return ActionEvent;
  52321. }());
  52322. BABYLON.ActionEvent = ActionEvent;
  52323. /**
  52324. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52325. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52326. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52327. */
  52328. var ActionManager = /** @class */ (function () {
  52329. /**
  52330. * Creates a new action manager
  52331. * @param scene defines the hosting scene
  52332. */
  52333. function ActionManager(scene) {
  52334. // Members
  52335. /** Gets the list of actions */
  52336. this.actions = new Array();
  52337. /** Gets the cursor to use when hovering items */
  52338. this.hoverCursor = '';
  52339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52340. scene._actionManagers.push(this);
  52341. }
  52342. Object.defineProperty(ActionManager, "NothingTrigger", {
  52343. /**
  52344. * Nothing
  52345. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52346. */
  52347. get: function () {
  52348. return ActionManager._NothingTrigger;
  52349. },
  52350. enumerable: true,
  52351. configurable: true
  52352. });
  52353. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52354. /**
  52355. * On pick
  52356. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52357. */
  52358. get: function () {
  52359. return ActionManager._OnPickTrigger;
  52360. },
  52361. enumerable: true,
  52362. configurable: true
  52363. });
  52364. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52365. /**
  52366. * On left pick
  52367. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52368. */
  52369. get: function () {
  52370. return ActionManager._OnLeftPickTrigger;
  52371. },
  52372. enumerable: true,
  52373. configurable: true
  52374. });
  52375. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52376. /**
  52377. * On right pick
  52378. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52379. */
  52380. get: function () {
  52381. return ActionManager._OnRightPickTrigger;
  52382. },
  52383. enumerable: true,
  52384. configurable: true
  52385. });
  52386. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52387. /**
  52388. * On center pick
  52389. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52390. */
  52391. get: function () {
  52392. return ActionManager._OnCenterPickTrigger;
  52393. },
  52394. enumerable: true,
  52395. configurable: true
  52396. });
  52397. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52398. /**
  52399. * On pick down
  52400. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52401. */
  52402. get: function () {
  52403. return ActionManager._OnPickDownTrigger;
  52404. },
  52405. enumerable: true,
  52406. configurable: true
  52407. });
  52408. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52409. /**
  52410. * On double pick
  52411. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52412. */
  52413. get: function () {
  52414. return ActionManager._OnDoublePickTrigger;
  52415. },
  52416. enumerable: true,
  52417. configurable: true
  52418. });
  52419. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52420. /**
  52421. * On pick up
  52422. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52423. */
  52424. get: function () {
  52425. return ActionManager._OnPickUpTrigger;
  52426. },
  52427. enumerable: true,
  52428. configurable: true
  52429. });
  52430. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52431. /**
  52432. * On pick out.
  52433. * This trigger will only be raised if you also declared a OnPickDown
  52434. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52435. */
  52436. get: function () {
  52437. return ActionManager._OnPickOutTrigger;
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52443. /**
  52444. * On long press
  52445. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52446. */
  52447. get: function () {
  52448. return ActionManager._OnLongPressTrigger;
  52449. },
  52450. enumerable: true,
  52451. configurable: true
  52452. });
  52453. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52454. /**
  52455. * On pointer over
  52456. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52457. */
  52458. get: function () {
  52459. return ActionManager._OnPointerOverTrigger;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52465. /**
  52466. * On pointer out
  52467. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52468. */
  52469. get: function () {
  52470. return ActionManager._OnPointerOutTrigger;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52476. /**
  52477. * On every frame
  52478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52479. */
  52480. get: function () {
  52481. return ActionManager._OnEveryFrameTrigger;
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52487. /**
  52488. * On intersection enter
  52489. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52490. */
  52491. get: function () {
  52492. return ActionManager._OnIntersectionEnterTrigger;
  52493. },
  52494. enumerable: true,
  52495. configurable: true
  52496. });
  52497. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52498. /**
  52499. * On intersection exit
  52500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52501. */
  52502. get: function () {
  52503. return ActionManager._OnIntersectionExitTrigger;
  52504. },
  52505. enumerable: true,
  52506. configurable: true
  52507. });
  52508. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52509. /**
  52510. * On key down
  52511. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52512. */
  52513. get: function () {
  52514. return ActionManager._OnKeyDownTrigger;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52520. /**
  52521. * On key up
  52522. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52523. */
  52524. get: function () {
  52525. return ActionManager._OnKeyUpTrigger;
  52526. },
  52527. enumerable: true,
  52528. configurable: true
  52529. });
  52530. // Methods
  52531. /**
  52532. * Releases all associated resources
  52533. */
  52534. ActionManager.prototype.dispose = function () {
  52535. var index = this._scene._actionManagers.indexOf(this);
  52536. for (var i = 0; i < this.actions.length; i++) {
  52537. var action = this.actions[i];
  52538. ActionManager.Triggers[action.trigger]--;
  52539. if (ActionManager.Triggers[action.trigger] === 0) {
  52540. delete ActionManager.Triggers[action.trigger];
  52541. }
  52542. }
  52543. if (index > -1) {
  52544. this._scene._actionManagers.splice(index, 1);
  52545. }
  52546. };
  52547. /**
  52548. * Gets hosting scene
  52549. * @returns the hosting scene
  52550. */
  52551. ActionManager.prototype.getScene = function () {
  52552. return this._scene;
  52553. };
  52554. /**
  52555. * Does this action manager handles actions of any of the given triggers
  52556. * @param triggers defines the triggers to be tested
  52557. * @return a boolean indicating whether one (or more) of the triggers is handled
  52558. */
  52559. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52560. for (var index = 0; index < this.actions.length; index++) {
  52561. var action = this.actions[index];
  52562. if (triggers.indexOf(action.trigger) > -1) {
  52563. return true;
  52564. }
  52565. }
  52566. return false;
  52567. };
  52568. /**
  52569. * Does this action manager handles actions of a given trigger
  52570. * @param trigger defines the trigger to be tested
  52571. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52572. * @return whether the trigger is handled
  52573. */
  52574. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52575. for (var index = 0; index < this.actions.length; index++) {
  52576. var action = this.actions[index];
  52577. if (action.trigger === trigger) {
  52578. if (parameterPredicate) {
  52579. if (parameterPredicate(action.getTriggerParameter())) {
  52580. return true;
  52581. }
  52582. }
  52583. else {
  52584. return true;
  52585. }
  52586. }
  52587. }
  52588. return false;
  52589. };
  52590. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52591. /**
  52592. * Does this action manager has pointer triggers
  52593. */
  52594. get: function () {
  52595. for (var index = 0; index < this.actions.length; index++) {
  52596. var action = this.actions[index];
  52597. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52598. return true;
  52599. }
  52600. }
  52601. return false;
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52607. /**
  52608. * Does this action manager has pick triggers
  52609. */
  52610. get: function () {
  52611. for (var index = 0; index < this.actions.length; index++) {
  52612. var action = this.actions[index];
  52613. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52614. return true;
  52615. }
  52616. }
  52617. return false;
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. Object.defineProperty(ActionManager, "HasTriggers", {
  52623. /**
  52624. * Does exist one action manager with at least one trigger
  52625. **/
  52626. get: function () {
  52627. for (var t in ActionManager.Triggers) {
  52628. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52629. return true;
  52630. }
  52631. }
  52632. return false;
  52633. },
  52634. enumerable: true,
  52635. configurable: true
  52636. });
  52637. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52638. /**
  52639. * Does exist one action manager with at least one pick trigger
  52640. **/
  52641. get: function () {
  52642. for (var t in ActionManager.Triggers) {
  52643. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52644. var t_int = parseInt(t);
  52645. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52646. return true;
  52647. }
  52648. }
  52649. }
  52650. return false;
  52651. },
  52652. enumerable: true,
  52653. configurable: true
  52654. });
  52655. /**
  52656. * Does exist one action manager that handles actions of a given trigger
  52657. * @param trigger defines the trigger to be tested
  52658. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52659. **/
  52660. ActionManager.HasSpecificTrigger = function (trigger) {
  52661. for (var t in ActionManager.Triggers) {
  52662. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52663. var t_int = parseInt(t);
  52664. if (t_int === trigger) {
  52665. return true;
  52666. }
  52667. }
  52668. }
  52669. return false;
  52670. };
  52671. /**
  52672. * Registers an action to this action manager
  52673. * @param action defines the action to be registered
  52674. * @return the action amended (prepared) after registration
  52675. */
  52676. ActionManager.prototype.registerAction = function (action) {
  52677. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52678. if (this.getScene().actionManager !== this) {
  52679. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52680. return null;
  52681. }
  52682. }
  52683. this.actions.push(action);
  52684. if (ActionManager.Triggers[action.trigger]) {
  52685. ActionManager.Triggers[action.trigger]++;
  52686. }
  52687. else {
  52688. ActionManager.Triggers[action.trigger] = 1;
  52689. }
  52690. action._actionManager = this;
  52691. action._prepare();
  52692. return action;
  52693. };
  52694. /**
  52695. * Unregisters an action to this action manager
  52696. * @param action defines the action to be unregistered
  52697. * @return a boolean indicating whether the action has been unregistered
  52698. */
  52699. ActionManager.prototype.unregisterAction = function (action) {
  52700. var index = this.actions.indexOf(action);
  52701. if (index !== -1) {
  52702. this.actions.splice(index, 1);
  52703. ActionManager.Triggers[action.trigger] -= 1;
  52704. if (ActionManager.Triggers[action.trigger] === 0) {
  52705. delete ActionManager.Triggers[action.trigger];
  52706. }
  52707. delete action._actionManager;
  52708. return true;
  52709. }
  52710. return false;
  52711. };
  52712. /**
  52713. * Process a specific trigger
  52714. * @param trigger defines the trigger to process
  52715. * @param evt defines the event details to be processed
  52716. */
  52717. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52718. for (var index = 0; index < this.actions.length; index++) {
  52719. var action = this.actions[index];
  52720. if (action.trigger === trigger) {
  52721. if (evt) {
  52722. if (trigger === ActionManager.OnKeyUpTrigger
  52723. || trigger === ActionManager.OnKeyDownTrigger) {
  52724. var parameter = action.getTriggerParameter();
  52725. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52726. if (!parameter.toLowerCase) {
  52727. continue;
  52728. }
  52729. var lowerCase = parameter.toLowerCase();
  52730. if (lowerCase !== evt.sourceEvent.key) {
  52731. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52732. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52733. if (actualkey !== lowerCase) {
  52734. continue;
  52735. }
  52736. }
  52737. }
  52738. }
  52739. }
  52740. action._executeCurrent(evt);
  52741. }
  52742. }
  52743. };
  52744. /** @hidden */
  52745. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52746. var properties = propertyPath.split(".");
  52747. for (var index = 0; index < properties.length - 1; index++) {
  52748. target = target[properties[index]];
  52749. }
  52750. return target;
  52751. };
  52752. /** @hidden */
  52753. ActionManager.prototype._getProperty = function (propertyPath) {
  52754. var properties = propertyPath.split(".");
  52755. return properties[properties.length - 1];
  52756. };
  52757. /**
  52758. * Serialize this manager to a JSON object
  52759. * @param name defines the property name to store this manager
  52760. * @returns a JSON representation of this manager
  52761. */
  52762. ActionManager.prototype.serialize = function (name) {
  52763. var root = {
  52764. children: new Array(),
  52765. name: name,
  52766. type: 3,
  52767. properties: new Array() // Empty for root but required
  52768. };
  52769. for (var i = 0; i < this.actions.length; i++) {
  52770. var triggerObject = {
  52771. type: 0,
  52772. children: new Array(),
  52773. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52774. properties: new Array()
  52775. };
  52776. var triggerOptions = this.actions[i].triggerOptions;
  52777. if (triggerOptions && typeof triggerOptions !== "number") {
  52778. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52779. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52780. }
  52781. else {
  52782. var parameter = {};
  52783. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52784. if (triggerOptions.parameter.mesh) {
  52785. parameter._meshId = triggerOptions.parameter.mesh.id;
  52786. }
  52787. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52788. }
  52789. }
  52790. // Serialize child action, recursively
  52791. this.actions[i].serialize(triggerObject);
  52792. // Add serialized trigger
  52793. root.children.push(triggerObject);
  52794. }
  52795. return root;
  52796. };
  52797. /**
  52798. * Creates a new ActionManager from a JSON data
  52799. * @param parsedActions defines the JSON data to read from
  52800. * @param object defines the hosting mesh
  52801. * @param scene defines the hosting scene
  52802. */
  52803. ActionManager.Parse = function (parsedActions, object, scene) {
  52804. var actionManager = new ActionManager(scene);
  52805. if (object === null)
  52806. scene.actionManager = actionManager;
  52807. else
  52808. object.actionManager = actionManager;
  52809. // instanciate a new object
  52810. var instanciate = function (name, params) {
  52811. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52812. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52813. newInstance.constructor.apply(newInstance, params);
  52814. return newInstance;
  52815. };
  52816. var parseParameter = function (name, value, target, propertyPath) {
  52817. if (propertyPath === null) {
  52818. // String, boolean or float
  52819. var floatValue = parseFloat(value);
  52820. if (value === "true" || value === "false")
  52821. return value === "true";
  52822. else
  52823. return isNaN(floatValue) ? value : floatValue;
  52824. }
  52825. var effectiveTarget = propertyPath.split(".");
  52826. var values = value.split(",");
  52827. // Get effective Target
  52828. for (var i = 0; i < effectiveTarget.length; i++) {
  52829. target = target[effectiveTarget[i]];
  52830. }
  52831. // Return appropriate value with its type
  52832. if (typeof (target) === "boolean")
  52833. return values[0] === "true";
  52834. if (typeof (target) === "string")
  52835. return values[0];
  52836. // Parameters with multiple values such as Vector3 etc.
  52837. var split = new Array();
  52838. for (var i = 0; i < values.length; i++)
  52839. split.push(parseFloat(values[i]));
  52840. if (target instanceof BABYLON.Vector3)
  52841. return BABYLON.Vector3.FromArray(split);
  52842. if (target instanceof BABYLON.Vector4)
  52843. return BABYLON.Vector4.FromArray(split);
  52844. if (target instanceof BABYLON.Color3)
  52845. return BABYLON.Color3.FromArray(split);
  52846. if (target instanceof BABYLON.Color4)
  52847. return BABYLON.Color4.FromArray(split);
  52848. return parseFloat(values[0]);
  52849. };
  52850. // traverse graph per trigger
  52851. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52852. if (combineArray === void 0) { combineArray = null; }
  52853. if (parsedAction.detached)
  52854. return;
  52855. var parameters = new Array();
  52856. var target = null;
  52857. var propertyPath = null;
  52858. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52859. // Parameters
  52860. if (parsedAction.type === 2)
  52861. parameters.push(actionManager);
  52862. else
  52863. parameters.push(trigger);
  52864. if (combine) {
  52865. var actions = new Array();
  52866. for (var j = 0; j < parsedAction.combine.length; j++) {
  52867. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52868. }
  52869. parameters.push(actions);
  52870. }
  52871. else {
  52872. for (var i = 0; i < parsedAction.properties.length; i++) {
  52873. var value = parsedAction.properties[i].value;
  52874. var name = parsedAction.properties[i].name;
  52875. var targetType = parsedAction.properties[i].targetType;
  52876. if (name === "target")
  52877. if (targetType !== null && targetType === "SceneProperties")
  52878. value = target = scene;
  52879. else
  52880. value = target = scene.getNodeByName(value);
  52881. else if (name === "parent")
  52882. value = scene.getNodeByName(value);
  52883. else if (name === "sound")
  52884. value = scene.getSoundByName(value);
  52885. else if (name !== "propertyPath") {
  52886. if (parsedAction.type === 2 && name === "operator")
  52887. value = BABYLON.ValueCondition[value];
  52888. else
  52889. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52890. }
  52891. else {
  52892. propertyPath = value;
  52893. }
  52894. parameters.push(value);
  52895. }
  52896. }
  52897. if (combineArray === null) {
  52898. parameters.push(condition);
  52899. }
  52900. else {
  52901. parameters.push(null);
  52902. }
  52903. // If interpolate value action
  52904. if (parsedAction.name === "InterpolateValueAction") {
  52905. var param = parameters[parameters.length - 2];
  52906. parameters[parameters.length - 1] = param;
  52907. parameters[parameters.length - 2] = condition;
  52908. }
  52909. // Action or condition(s) and not CombineAction
  52910. var newAction = instanciate(parsedAction.name, parameters);
  52911. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52912. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52913. if (action)
  52914. action.then(nothing);
  52915. else
  52916. actionManager.registerAction(nothing);
  52917. action = nothing;
  52918. }
  52919. if (combineArray === null) {
  52920. if (newAction instanceof BABYLON.Condition) {
  52921. condition = newAction;
  52922. newAction = action;
  52923. }
  52924. else {
  52925. condition = null;
  52926. if (action)
  52927. action.then(newAction);
  52928. else
  52929. actionManager.registerAction(newAction);
  52930. }
  52931. }
  52932. else {
  52933. combineArray.push(newAction);
  52934. }
  52935. for (var i = 0; i < parsedAction.children.length; i++)
  52936. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52937. };
  52938. // triggers
  52939. for (var i = 0; i < parsedActions.children.length; i++) {
  52940. var triggerParams;
  52941. var trigger = parsedActions.children[i];
  52942. if (trigger.properties.length > 0) {
  52943. var param = trigger.properties[0].value;
  52944. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52945. if (value._meshId) {
  52946. value.mesh = scene.getMeshByID(value._meshId);
  52947. }
  52948. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52949. }
  52950. else
  52951. triggerParams = ActionManager[trigger.name];
  52952. for (var j = 0; j < trigger.children.length; j++) {
  52953. if (!trigger.detached)
  52954. traverse(trigger.children[j], triggerParams, null, null);
  52955. }
  52956. }
  52957. };
  52958. /**
  52959. * Get a trigger name by index
  52960. * @param trigger defines the trigger index
  52961. * @returns a trigger name
  52962. */
  52963. ActionManager.GetTriggerName = function (trigger) {
  52964. switch (trigger) {
  52965. case 0: return "NothingTrigger";
  52966. case 1: return "OnPickTrigger";
  52967. case 2: return "OnLeftPickTrigger";
  52968. case 3: return "OnRightPickTrigger";
  52969. case 4: return "OnCenterPickTrigger";
  52970. case 5: return "OnPickDownTrigger";
  52971. case 6: return "OnPickUpTrigger";
  52972. case 7: return "OnLongPressTrigger";
  52973. case 8: return "OnPointerOverTrigger";
  52974. case 9: return "OnPointerOutTrigger";
  52975. case 10: return "OnEveryFrameTrigger";
  52976. case 11: return "OnIntersectionEnterTrigger";
  52977. case 12: return "OnIntersectionExitTrigger";
  52978. case 13: return "OnKeyDownTrigger";
  52979. case 14: return "OnKeyUpTrigger";
  52980. case 15: return "OnPickOutTrigger";
  52981. default: return "";
  52982. }
  52983. };
  52984. // Statics
  52985. ActionManager._NothingTrigger = 0;
  52986. ActionManager._OnPickTrigger = 1;
  52987. ActionManager._OnLeftPickTrigger = 2;
  52988. ActionManager._OnRightPickTrigger = 3;
  52989. ActionManager._OnCenterPickTrigger = 4;
  52990. ActionManager._OnPickDownTrigger = 5;
  52991. ActionManager._OnDoublePickTrigger = 6;
  52992. ActionManager._OnPickUpTrigger = 7;
  52993. ActionManager._OnLongPressTrigger = 8;
  52994. ActionManager._OnPointerOverTrigger = 9;
  52995. ActionManager._OnPointerOutTrigger = 10;
  52996. ActionManager._OnEveryFrameTrigger = 11;
  52997. ActionManager._OnIntersectionEnterTrigger = 12;
  52998. ActionManager._OnIntersectionExitTrigger = 13;
  52999. ActionManager._OnKeyDownTrigger = 14;
  53000. ActionManager._OnKeyUpTrigger = 15;
  53001. ActionManager._OnPickOutTrigger = 16;
  53002. /** Gets the list of active triggers */
  53003. ActionManager.Triggers = {};
  53004. return ActionManager;
  53005. }());
  53006. BABYLON.ActionManager = ActionManager;
  53007. })(BABYLON || (BABYLON = {}));
  53008. //# sourceMappingURL=babylon.actionManager.js.map
  53009. var BABYLON;
  53010. (function (BABYLON) {
  53011. var InterpolateValueAction = /** @class */ (function (_super) {
  53012. __extends(InterpolateValueAction, _super);
  53013. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53014. if (duration === void 0) { duration = 1000; }
  53015. var _this = _super.call(this, triggerOptions, condition) || this;
  53016. _this.propertyPath = propertyPath;
  53017. _this.value = value;
  53018. _this.duration = duration;
  53019. _this.stopOtherAnimations = stopOtherAnimations;
  53020. _this.onInterpolationDone = onInterpolationDone;
  53021. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53022. _this._target = _this._effectiveTarget = target;
  53023. return _this;
  53024. }
  53025. InterpolateValueAction.prototype._prepare = function () {
  53026. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53027. this._property = this._getProperty(this.propertyPath);
  53028. };
  53029. InterpolateValueAction.prototype.execute = function () {
  53030. var _this = this;
  53031. var scene = this._actionManager.getScene();
  53032. var keys = [
  53033. {
  53034. frame: 0,
  53035. value: this._effectiveTarget[this._property]
  53036. }, {
  53037. frame: 100,
  53038. value: this.value
  53039. }
  53040. ];
  53041. var dataType;
  53042. if (typeof this.value === "number") {
  53043. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53044. }
  53045. else if (this.value instanceof BABYLON.Color3) {
  53046. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53047. }
  53048. else if (this.value instanceof BABYLON.Vector3) {
  53049. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53050. }
  53051. else if (this.value instanceof BABYLON.Matrix) {
  53052. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53053. }
  53054. else if (this.value instanceof BABYLON.Quaternion) {
  53055. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53056. }
  53057. else {
  53058. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53059. return;
  53060. }
  53061. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53062. animation.setKeys(keys);
  53063. if (this.stopOtherAnimations) {
  53064. scene.stopAnimation(this._effectiveTarget);
  53065. }
  53066. var wrapper = function () {
  53067. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53068. if (_this.onInterpolationDone) {
  53069. _this.onInterpolationDone();
  53070. }
  53071. };
  53072. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53073. };
  53074. InterpolateValueAction.prototype.serialize = function (parent) {
  53075. return _super.prototype._serialize.call(this, {
  53076. name: "InterpolateValueAction",
  53077. properties: [
  53078. BABYLON.Action._GetTargetProperty(this._target),
  53079. { name: "propertyPath", value: this.propertyPath },
  53080. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53081. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53082. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53083. ]
  53084. }, parent);
  53085. };
  53086. return InterpolateValueAction;
  53087. }(BABYLON.Action));
  53088. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53089. })(BABYLON || (BABYLON = {}));
  53090. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53091. var BABYLON;
  53092. (function (BABYLON) {
  53093. var SwitchBooleanAction = /** @class */ (function (_super) {
  53094. __extends(SwitchBooleanAction, _super);
  53095. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53096. var _this = _super.call(this, triggerOptions, condition) || this;
  53097. _this.propertyPath = propertyPath;
  53098. _this._target = _this._effectiveTarget = target;
  53099. return _this;
  53100. }
  53101. SwitchBooleanAction.prototype._prepare = function () {
  53102. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53103. this._property = this._getProperty(this.propertyPath);
  53104. };
  53105. SwitchBooleanAction.prototype.execute = function () {
  53106. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53107. };
  53108. SwitchBooleanAction.prototype.serialize = function (parent) {
  53109. return _super.prototype._serialize.call(this, {
  53110. name: "SwitchBooleanAction",
  53111. properties: [
  53112. BABYLON.Action._GetTargetProperty(this._target),
  53113. { name: "propertyPath", value: this.propertyPath }
  53114. ]
  53115. }, parent);
  53116. };
  53117. return SwitchBooleanAction;
  53118. }(BABYLON.Action));
  53119. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53120. var SetStateAction = /** @class */ (function (_super) {
  53121. __extends(SetStateAction, _super);
  53122. function SetStateAction(triggerOptions, target, value, condition) {
  53123. var _this = _super.call(this, triggerOptions, condition) || this;
  53124. _this.value = value;
  53125. _this._target = target;
  53126. return _this;
  53127. }
  53128. SetStateAction.prototype.execute = function () {
  53129. this._target.state = this.value;
  53130. };
  53131. SetStateAction.prototype.serialize = function (parent) {
  53132. return _super.prototype._serialize.call(this, {
  53133. name: "SetStateAction",
  53134. properties: [
  53135. BABYLON.Action._GetTargetProperty(this._target),
  53136. { name: "value", value: this.value }
  53137. ]
  53138. }, parent);
  53139. };
  53140. return SetStateAction;
  53141. }(BABYLON.Action));
  53142. BABYLON.SetStateAction = SetStateAction;
  53143. var SetValueAction = /** @class */ (function (_super) {
  53144. __extends(SetValueAction, _super);
  53145. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53146. var _this = _super.call(this, triggerOptions, condition) || this;
  53147. _this.propertyPath = propertyPath;
  53148. _this.value = value;
  53149. _this._target = _this._effectiveTarget = target;
  53150. return _this;
  53151. }
  53152. SetValueAction.prototype._prepare = function () {
  53153. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53154. this._property = this._getProperty(this.propertyPath);
  53155. };
  53156. SetValueAction.prototype.execute = function () {
  53157. this._effectiveTarget[this._property] = this.value;
  53158. if (this._target.markAsDirty) {
  53159. this._target.markAsDirty(this._property);
  53160. }
  53161. };
  53162. SetValueAction.prototype.serialize = function (parent) {
  53163. return _super.prototype._serialize.call(this, {
  53164. name: "SetValueAction",
  53165. properties: [
  53166. BABYLON.Action._GetTargetProperty(this._target),
  53167. { name: "propertyPath", value: this.propertyPath },
  53168. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53169. ]
  53170. }, parent);
  53171. };
  53172. return SetValueAction;
  53173. }(BABYLON.Action));
  53174. BABYLON.SetValueAction = SetValueAction;
  53175. var IncrementValueAction = /** @class */ (function (_super) {
  53176. __extends(IncrementValueAction, _super);
  53177. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53178. var _this = _super.call(this, triggerOptions, condition) || this;
  53179. _this.propertyPath = propertyPath;
  53180. _this.value = value;
  53181. _this._target = _this._effectiveTarget = target;
  53182. return _this;
  53183. }
  53184. IncrementValueAction.prototype._prepare = function () {
  53185. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53186. this._property = this._getProperty(this.propertyPath);
  53187. if (typeof this._effectiveTarget[this._property] !== "number") {
  53188. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53189. }
  53190. };
  53191. IncrementValueAction.prototype.execute = function () {
  53192. this._effectiveTarget[this._property] += this.value;
  53193. if (this._target.markAsDirty) {
  53194. this._target.markAsDirty(this._property);
  53195. }
  53196. };
  53197. IncrementValueAction.prototype.serialize = function (parent) {
  53198. return _super.prototype._serialize.call(this, {
  53199. name: "IncrementValueAction",
  53200. properties: [
  53201. BABYLON.Action._GetTargetProperty(this._target),
  53202. { name: "propertyPath", value: this.propertyPath },
  53203. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53204. ]
  53205. }, parent);
  53206. };
  53207. return IncrementValueAction;
  53208. }(BABYLON.Action));
  53209. BABYLON.IncrementValueAction = IncrementValueAction;
  53210. var PlayAnimationAction = /** @class */ (function (_super) {
  53211. __extends(PlayAnimationAction, _super);
  53212. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53213. var _this = _super.call(this, triggerOptions, condition) || this;
  53214. _this.from = from;
  53215. _this.to = to;
  53216. _this.loop = loop;
  53217. _this._target = target;
  53218. return _this;
  53219. }
  53220. PlayAnimationAction.prototype._prepare = function () {
  53221. };
  53222. PlayAnimationAction.prototype.execute = function () {
  53223. var scene = this._actionManager.getScene();
  53224. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53225. };
  53226. PlayAnimationAction.prototype.serialize = function (parent) {
  53227. return _super.prototype._serialize.call(this, {
  53228. name: "PlayAnimationAction",
  53229. properties: [
  53230. BABYLON.Action._GetTargetProperty(this._target),
  53231. { name: "from", value: String(this.from) },
  53232. { name: "to", value: String(this.to) },
  53233. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53234. ]
  53235. }, parent);
  53236. };
  53237. return PlayAnimationAction;
  53238. }(BABYLON.Action));
  53239. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53240. var StopAnimationAction = /** @class */ (function (_super) {
  53241. __extends(StopAnimationAction, _super);
  53242. function StopAnimationAction(triggerOptions, target, condition) {
  53243. var _this = _super.call(this, triggerOptions, condition) || this;
  53244. _this._target = target;
  53245. return _this;
  53246. }
  53247. StopAnimationAction.prototype._prepare = function () {
  53248. };
  53249. StopAnimationAction.prototype.execute = function () {
  53250. var scene = this._actionManager.getScene();
  53251. scene.stopAnimation(this._target);
  53252. };
  53253. StopAnimationAction.prototype.serialize = function (parent) {
  53254. return _super.prototype._serialize.call(this, {
  53255. name: "StopAnimationAction",
  53256. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53257. }, parent);
  53258. };
  53259. return StopAnimationAction;
  53260. }(BABYLON.Action));
  53261. BABYLON.StopAnimationAction = StopAnimationAction;
  53262. var DoNothingAction = /** @class */ (function (_super) {
  53263. __extends(DoNothingAction, _super);
  53264. function DoNothingAction(triggerOptions, condition) {
  53265. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53266. return _super.call(this, triggerOptions, condition) || this;
  53267. }
  53268. DoNothingAction.prototype.execute = function () {
  53269. };
  53270. DoNothingAction.prototype.serialize = function (parent) {
  53271. return _super.prototype._serialize.call(this, {
  53272. name: "DoNothingAction",
  53273. properties: []
  53274. }, parent);
  53275. };
  53276. return DoNothingAction;
  53277. }(BABYLON.Action));
  53278. BABYLON.DoNothingAction = DoNothingAction;
  53279. var CombineAction = /** @class */ (function (_super) {
  53280. __extends(CombineAction, _super);
  53281. function CombineAction(triggerOptions, children, condition) {
  53282. var _this = _super.call(this, triggerOptions, condition) || this;
  53283. _this.children = children;
  53284. return _this;
  53285. }
  53286. CombineAction.prototype._prepare = function () {
  53287. for (var index = 0; index < this.children.length; index++) {
  53288. this.children[index]._actionManager = this._actionManager;
  53289. this.children[index]._prepare();
  53290. }
  53291. };
  53292. CombineAction.prototype.execute = function (evt) {
  53293. for (var index = 0; index < this.children.length; index++) {
  53294. this.children[index].execute(evt);
  53295. }
  53296. };
  53297. CombineAction.prototype.serialize = function (parent) {
  53298. var serializationObject = _super.prototype._serialize.call(this, {
  53299. name: "CombineAction",
  53300. properties: [],
  53301. combine: []
  53302. }, parent);
  53303. for (var i = 0; i < this.children.length; i++) {
  53304. serializationObject.combine.push(this.children[i].serialize(null));
  53305. }
  53306. return serializationObject;
  53307. };
  53308. return CombineAction;
  53309. }(BABYLON.Action));
  53310. BABYLON.CombineAction = CombineAction;
  53311. var ExecuteCodeAction = /** @class */ (function (_super) {
  53312. __extends(ExecuteCodeAction, _super);
  53313. function ExecuteCodeAction(triggerOptions, func, condition) {
  53314. var _this = _super.call(this, triggerOptions, condition) || this;
  53315. _this.func = func;
  53316. return _this;
  53317. }
  53318. ExecuteCodeAction.prototype.execute = function (evt) {
  53319. this.func(evt);
  53320. };
  53321. return ExecuteCodeAction;
  53322. }(BABYLON.Action));
  53323. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53324. var SetParentAction = /** @class */ (function (_super) {
  53325. __extends(SetParentAction, _super);
  53326. function SetParentAction(triggerOptions, target, parent, condition) {
  53327. var _this = _super.call(this, triggerOptions, condition) || this;
  53328. _this._target = target;
  53329. _this._parent = parent;
  53330. return _this;
  53331. }
  53332. SetParentAction.prototype._prepare = function () {
  53333. };
  53334. SetParentAction.prototype.execute = function () {
  53335. if (this._target.parent === this._parent) {
  53336. return;
  53337. }
  53338. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53339. invertParentWorldMatrix.invert();
  53340. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53341. this._target.parent = this._parent;
  53342. };
  53343. SetParentAction.prototype.serialize = function (parent) {
  53344. return _super.prototype._serialize.call(this, {
  53345. name: "SetParentAction",
  53346. properties: [
  53347. BABYLON.Action._GetTargetProperty(this._target),
  53348. BABYLON.Action._GetTargetProperty(this._parent),
  53349. ]
  53350. }, parent);
  53351. };
  53352. return SetParentAction;
  53353. }(BABYLON.Action));
  53354. BABYLON.SetParentAction = SetParentAction;
  53355. var PlaySoundAction = /** @class */ (function (_super) {
  53356. __extends(PlaySoundAction, _super);
  53357. function PlaySoundAction(triggerOptions, sound, condition) {
  53358. var _this = _super.call(this, triggerOptions, condition) || this;
  53359. _this._sound = sound;
  53360. return _this;
  53361. }
  53362. PlaySoundAction.prototype._prepare = function () {
  53363. };
  53364. PlaySoundAction.prototype.execute = function () {
  53365. if (this._sound !== undefined)
  53366. this._sound.play();
  53367. };
  53368. PlaySoundAction.prototype.serialize = function (parent) {
  53369. return _super.prototype._serialize.call(this, {
  53370. name: "PlaySoundAction",
  53371. properties: [{ name: "sound", value: this._sound.name }]
  53372. }, parent);
  53373. };
  53374. return PlaySoundAction;
  53375. }(BABYLON.Action));
  53376. BABYLON.PlaySoundAction = PlaySoundAction;
  53377. var StopSoundAction = /** @class */ (function (_super) {
  53378. __extends(StopSoundAction, _super);
  53379. function StopSoundAction(triggerOptions, sound, condition) {
  53380. var _this = _super.call(this, triggerOptions, condition) || this;
  53381. _this._sound = sound;
  53382. return _this;
  53383. }
  53384. StopSoundAction.prototype._prepare = function () {
  53385. };
  53386. StopSoundAction.prototype.execute = function () {
  53387. if (this._sound !== undefined)
  53388. this._sound.stop();
  53389. };
  53390. StopSoundAction.prototype.serialize = function (parent) {
  53391. return _super.prototype._serialize.call(this, {
  53392. name: "StopSoundAction",
  53393. properties: [{ name: "sound", value: this._sound.name }]
  53394. }, parent);
  53395. };
  53396. return StopSoundAction;
  53397. }(BABYLON.Action));
  53398. BABYLON.StopSoundAction = StopSoundAction;
  53399. })(BABYLON || (BABYLON = {}));
  53400. //# sourceMappingURL=babylon.directActions.js.map
  53401. var BABYLON;
  53402. (function (BABYLON) {
  53403. var SpriteManager = /** @class */ (function () {
  53404. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53405. if (epsilon === void 0) { epsilon = 0.01; }
  53406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53407. this.name = name;
  53408. this.sprites = new Array();
  53409. this.renderingGroupId = 0;
  53410. this.layerMask = 0x0FFFFFFF;
  53411. this.fogEnabled = true;
  53412. this.isPickable = false;
  53413. /**
  53414. * An event triggered when the manager is disposed.
  53415. */
  53416. this.onDisposeObservable = new BABYLON.Observable();
  53417. this._vertexBuffers = {};
  53418. this._capacity = capacity;
  53419. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53420. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53421. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53422. if (cellSize.width && cellSize.height) {
  53423. this.cellWidth = cellSize.width;
  53424. this.cellHeight = cellSize.height;
  53425. }
  53426. else if (cellSize !== undefined) {
  53427. this.cellWidth = cellSize;
  53428. this.cellHeight = cellSize;
  53429. }
  53430. else {
  53431. return;
  53432. }
  53433. this._epsilon = epsilon;
  53434. this._scene = scene;
  53435. this._scene.spriteManagers.push(this);
  53436. var indices = [];
  53437. var index = 0;
  53438. for (var count = 0; count < capacity; count++) {
  53439. indices.push(index);
  53440. indices.push(index + 1);
  53441. indices.push(index + 2);
  53442. indices.push(index);
  53443. indices.push(index + 2);
  53444. indices.push(index + 3);
  53445. index += 4;
  53446. }
  53447. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53448. // VBO
  53449. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53450. this._vertexData = new Float32Array(capacity * 16 * 4);
  53451. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53452. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53453. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53454. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53455. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53457. this._vertexBuffers["options"] = options;
  53458. this._vertexBuffers["cellInfo"] = cellInfo;
  53459. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53460. // Effects
  53461. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53462. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53463. }
  53464. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53465. set: function (callback) {
  53466. if (this._onDisposeObserver) {
  53467. this.onDisposeObservable.remove(this._onDisposeObserver);
  53468. }
  53469. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53470. },
  53471. enumerable: true,
  53472. configurable: true
  53473. });
  53474. Object.defineProperty(SpriteManager.prototype, "texture", {
  53475. get: function () {
  53476. return this._spriteTexture;
  53477. },
  53478. set: function (value) {
  53479. this._spriteTexture = value;
  53480. },
  53481. enumerable: true,
  53482. configurable: true
  53483. });
  53484. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53485. var arrayOffset = index * 16;
  53486. if (offsetX === 0)
  53487. offsetX = this._epsilon;
  53488. else if (offsetX === 1)
  53489. offsetX = 1 - this._epsilon;
  53490. if (offsetY === 0)
  53491. offsetY = this._epsilon;
  53492. else if (offsetY === 1)
  53493. offsetY = 1 - this._epsilon;
  53494. this._vertexData[arrayOffset] = sprite.position.x;
  53495. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53496. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53497. this._vertexData[arrayOffset + 3] = sprite.angle;
  53498. this._vertexData[arrayOffset + 4] = sprite.width;
  53499. this._vertexData[arrayOffset + 5] = sprite.height;
  53500. this._vertexData[arrayOffset + 6] = offsetX;
  53501. this._vertexData[arrayOffset + 7] = offsetY;
  53502. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53503. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53504. var offset = (sprite.cellIndex / rowSize) >> 0;
  53505. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53506. this._vertexData[arrayOffset + 11] = offset;
  53507. // Color
  53508. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53509. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53510. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53511. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53512. };
  53513. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53514. var count = Math.min(this._capacity, this.sprites.length);
  53515. var min = BABYLON.Vector3.Zero();
  53516. var max = BABYLON.Vector3.Zero();
  53517. var distance = Number.MAX_VALUE;
  53518. var currentSprite = null;
  53519. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53520. var cameraView = camera.getViewMatrix();
  53521. for (var index = 0; index < count; index++) {
  53522. var sprite = this.sprites[index];
  53523. if (!sprite) {
  53524. continue;
  53525. }
  53526. if (predicate) {
  53527. if (!predicate(sprite)) {
  53528. continue;
  53529. }
  53530. }
  53531. else if (!sprite.isPickable) {
  53532. continue;
  53533. }
  53534. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53535. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53536. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53537. if (ray.intersectsBoxMinMax(min, max)) {
  53538. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53539. if (distance > currentDistance) {
  53540. distance = currentDistance;
  53541. currentSprite = sprite;
  53542. if (fastCheck) {
  53543. break;
  53544. }
  53545. }
  53546. }
  53547. }
  53548. if (currentSprite) {
  53549. var result = new BABYLON.PickingInfo();
  53550. result.hit = true;
  53551. result.pickedSprite = currentSprite;
  53552. result.distance = distance;
  53553. return result;
  53554. }
  53555. return null;
  53556. };
  53557. SpriteManager.prototype.render = function () {
  53558. // Check
  53559. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53560. return;
  53561. var engine = this._scene.getEngine();
  53562. var baseSize = this._spriteTexture.getBaseSize();
  53563. // Sprites
  53564. var deltaTime = engine.getDeltaTime();
  53565. var max = Math.min(this._capacity, this.sprites.length);
  53566. var rowSize = baseSize.width / this.cellWidth;
  53567. var offset = 0;
  53568. for (var index = 0; index < max; index++) {
  53569. var sprite = this.sprites[index];
  53570. if (!sprite || !sprite.isVisible) {
  53571. continue;
  53572. }
  53573. sprite._animate(deltaTime);
  53574. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53575. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53576. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53577. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53578. }
  53579. this._buffer.update(this._vertexData);
  53580. // Render
  53581. var effect = this._effectBase;
  53582. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53583. effect = this._effectFog;
  53584. }
  53585. engine.enableEffect(effect);
  53586. var viewMatrix = this._scene.getViewMatrix();
  53587. effect.setTexture("diffuseSampler", this._spriteTexture);
  53588. effect.setMatrix("view", viewMatrix);
  53589. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53590. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53591. // Fog
  53592. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53593. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53594. effect.setColor3("vFogColor", this._scene.fogColor);
  53595. }
  53596. // VBOs
  53597. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53598. // Draw order
  53599. engine.setDepthFunctionToLessOrEqual();
  53600. effect.setBool("alphaTest", true);
  53601. engine.setColorWrite(false);
  53602. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53603. engine.setColorWrite(true);
  53604. effect.setBool("alphaTest", false);
  53605. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53606. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53607. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53608. };
  53609. SpriteManager.prototype.dispose = function () {
  53610. if (this._buffer) {
  53611. this._buffer.dispose();
  53612. this._buffer = null;
  53613. }
  53614. if (this._indexBuffer) {
  53615. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53616. this._indexBuffer = null;
  53617. }
  53618. if (this._spriteTexture) {
  53619. this._spriteTexture.dispose();
  53620. this._spriteTexture = null;
  53621. }
  53622. // Remove from scene
  53623. var index = this._scene.spriteManagers.indexOf(this);
  53624. this._scene.spriteManagers.splice(index, 1);
  53625. // Callback
  53626. this.onDisposeObservable.notifyObservers(this);
  53627. this.onDisposeObservable.clear();
  53628. };
  53629. return SpriteManager;
  53630. }());
  53631. BABYLON.SpriteManager = SpriteManager;
  53632. })(BABYLON || (BABYLON = {}));
  53633. //# sourceMappingURL=babylon.spriteManager.js.map
  53634. var BABYLON;
  53635. (function (BABYLON) {
  53636. var Sprite = /** @class */ (function () {
  53637. function Sprite(name, manager) {
  53638. this.name = name;
  53639. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53640. this.width = 1.0;
  53641. this.height = 1.0;
  53642. this.angle = 0;
  53643. this.cellIndex = 0;
  53644. this.invertU = 0;
  53645. this.invertV = 0;
  53646. this.animations = new Array();
  53647. this.isPickable = false;
  53648. this._animationStarted = false;
  53649. this._loopAnimation = false;
  53650. this._fromIndex = 0;
  53651. this._toIndex = 0;
  53652. this._delay = 0;
  53653. this._direction = 1;
  53654. this._time = 0;
  53655. /**
  53656. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53657. */
  53658. this.isVisible = true;
  53659. this._manager = manager;
  53660. this._manager.sprites.push(this);
  53661. this.position = BABYLON.Vector3.Zero();
  53662. }
  53663. Object.defineProperty(Sprite.prototype, "size", {
  53664. get: function () {
  53665. return this.width;
  53666. },
  53667. set: function (value) {
  53668. this.width = value;
  53669. this.height = value;
  53670. },
  53671. enumerable: true,
  53672. configurable: true
  53673. });
  53674. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53675. this._fromIndex = from;
  53676. this._toIndex = to;
  53677. this._loopAnimation = loop;
  53678. this._delay = delay;
  53679. this._animationStarted = true;
  53680. this._direction = from < to ? 1 : -1;
  53681. this.cellIndex = from;
  53682. this._time = 0;
  53683. this._onAnimationEnd = onAnimationEnd;
  53684. };
  53685. Sprite.prototype.stopAnimation = function () {
  53686. this._animationStarted = false;
  53687. };
  53688. Sprite.prototype._animate = function (deltaTime) {
  53689. if (!this._animationStarted)
  53690. return;
  53691. this._time += deltaTime;
  53692. if (this._time > this._delay) {
  53693. this._time = this._time % this._delay;
  53694. this.cellIndex += this._direction;
  53695. if (this.cellIndex > this._toIndex) {
  53696. if (this._loopAnimation) {
  53697. this.cellIndex = this._fromIndex;
  53698. }
  53699. else {
  53700. this.cellIndex = this._toIndex;
  53701. this._animationStarted = false;
  53702. if (this._onAnimationEnd) {
  53703. this._onAnimationEnd();
  53704. }
  53705. if (this.disposeWhenFinishedAnimating) {
  53706. this.dispose();
  53707. }
  53708. }
  53709. }
  53710. }
  53711. };
  53712. Sprite.prototype.dispose = function () {
  53713. for (var i = 0; i < this._manager.sprites.length; i++) {
  53714. if (this._manager.sprites[i] == this) {
  53715. this._manager.sprites.splice(i, 1);
  53716. }
  53717. }
  53718. };
  53719. return Sprite;
  53720. }());
  53721. BABYLON.Sprite = Sprite;
  53722. })(BABYLON || (BABYLON = {}));
  53723. //# sourceMappingURL=babylon.sprite.js.map
  53724. var BABYLON;
  53725. (function (BABYLON) {
  53726. var IntersectionInfo = /** @class */ (function () {
  53727. function IntersectionInfo(bu, bv, distance) {
  53728. this.bu = bu;
  53729. this.bv = bv;
  53730. this.distance = distance;
  53731. this.faceId = 0;
  53732. this.subMeshId = 0;
  53733. }
  53734. return IntersectionInfo;
  53735. }());
  53736. BABYLON.IntersectionInfo = IntersectionInfo;
  53737. /**
  53738. * Information about the result of picking within a scene
  53739. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53740. */
  53741. var PickingInfo = /** @class */ (function () {
  53742. function PickingInfo() {
  53743. /**
  53744. * If the pick collided with an object
  53745. */
  53746. this.hit = false;
  53747. /**
  53748. * Distance away where the pick collided
  53749. */
  53750. this.distance = 0;
  53751. /**
  53752. * The location of pick collision
  53753. */
  53754. this.pickedPoint = null;
  53755. /**
  53756. * The mesh corrisponding the the pick collision
  53757. */
  53758. this.pickedMesh = null;
  53759. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53760. this.bu = 0;
  53761. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53762. this.bv = 0;
  53763. /** The id of the face on the mesh that was picked */
  53764. this.faceId = -1;
  53765. /** Id of the the submesh that was picked */
  53766. this.subMeshId = 0;
  53767. /** If a sprite was picked, this will be the sprite the pick collided with */
  53768. this.pickedSprite = null;
  53769. /**
  53770. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53771. */
  53772. this.originMesh = null;
  53773. /**
  53774. * The ray that was used to perform the picking.
  53775. */
  53776. this.ray = null;
  53777. }
  53778. /**
  53779. * Gets the normal corrispodning to the face the pick collided with
  53780. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53781. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53782. * @returns The normal corrispodning to the face the pick collided with
  53783. */
  53784. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53785. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53786. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53787. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53788. return null;
  53789. }
  53790. var indices = this.pickedMesh.getIndices();
  53791. if (!indices) {
  53792. return null;
  53793. }
  53794. var result;
  53795. if (useVerticesNormals) {
  53796. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53797. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53798. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53799. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53800. normal0 = normal0.scale(this.bu);
  53801. normal1 = normal1.scale(this.bv);
  53802. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53803. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53804. }
  53805. else {
  53806. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53807. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53808. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53809. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53810. var p1p2 = vertex1.subtract(vertex2);
  53811. var p3p2 = vertex3.subtract(vertex2);
  53812. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53813. }
  53814. if (useWorldCoordinates) {
  53815. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53816. }
  53817. return BABYLON.Vector3.Normalize(result);
  53818. };
  53819. /**
  53820. * Gets the texture coordinates of where the pick occured
  53821. * @returns the vector containing the coordnates of the texture
  53822. */
  53823. PickingInfo.prototype.getTextureCoordinates = function () {
  53824. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53825. return null;
  53826. }
  53827. var indices = this.pickedMesh.getIndices();
  53828. if (!indices) {
  53829. return null;
  53830. }
  53831. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53832. if (!uvs) {
  53833. return null;
  53834. }
  53835. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53836. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53837. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53838. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53839. uv1 = uv1.scale(this.bu);
  53840. uv2 = uv2.scale(this.bv);
  53841. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53842. };
  53843. return PickingInfo;
  53844. }());
  53845. BABYLON.PickingInfo = PickingInfo;
  53846. })(BABYLON || (BABYLON = {}));
  53847. //# sourceMappingURL=babylon.pickingInfo.js.map
  53848. var BABYLON;
  53849. (function (BABYLON) {
  53850. var Ray = /** @class */ (function () {
  53851. function Ray(origin, direction, length) {
  53852. if (length === void 0) { length = Number.MAX_VALUE; }
  53853. this.origin = origin;
  53854. this.direction = direction;
  53855. this.length = length;
  53856. }
  53857. // Methods
  53858. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53859. var d = 0.0;
  53860. var maxValue = Number.MAX_VALUE;
  53861. var inv;
  53862. var min;
  53863. var max;
  53864. var temp;
  53865. if (Math.abs(this.direction.x) < 0.0000001) {
  53866. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53867. return false;
  53868. }
  53869. }
  53870. else {
  53871. inv = 1.0 / this.direction.x;
  53872. min = (minimum.x - this.origin.x) * inv;
  53873. max = (maximum.x - this.origin.x) * inv;
  53874. if (max === -Infinity) {
  53875. max = Infinity;
  53876. }
  53877. if (min > max) {
  53878. temp = min;
  53879. min = max;
  53880. max = temp;
  53881. }
  53882. d = Math.max(min, d);
  53883. maxValue = Math.min(max, maxValue);
  53884. if (d > maxValue) {
  53885. return false;
  53886. }
  53887. }
  53888. if (Math.abs(this.direction.y) < 0.0000001) {
  53889. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53890. return false;
  53891. }
  53892. }
  53893. else {
  53894. inv = 1.0 / this.direction.y;
  53895. min = (minimum.y - this.origin.y) * inv;
  53896. max = (maximum.y - this.origin.y) * inv;
  53897. if (max === -Infinity) {
  53898. max = Infinity;
  53899. }
  53900. if (min > max) {
  53901. temp = min;
  53902. min = max;
  53903. max = temp;
  53904. }
  53905. d = Math.max(min, d);
  53906. maxValue = Math.min(max, maxValue);
  53907. if (d > maxValue) {
  53908. return false;
  53909. }
  53910. }
  53911. if (Math.abs(this.direction.z) < 0.0000001) {
  53912. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53913. return false;
  53914. }
  53915. }
  53916. else {
  53917. inv = 1.0 / this.direction.z;
  53918. min = (minimum.z - this.origin.z) * inv;
  53919. max = (maximum.z - this.origin.z) * inv;
  53920. if (max === -Infinity) {
  53921. max = Infinity;
  53922. }
  53923. if (min > max) {
  53924. temp = min;
  53925. min = max;
  53926. max = temp;
  53927. }
  53928. d = Math.max(min, d);
  53929. maxValue = Math.min(max, maxValue);
  53930. if (d > maxValue) {
  53931. return false;
  53932. }
  53933. }
  53934. return true;
  53935. };
  53936. Ray.prototype.intersectsBox = function (box) {
  53937. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53938. };
  53939. Ray.prototype.intersectsSphere = function (sphere) {
  53940. var x = sphere.center.x - this.origin.x;
  53941. var y = sphere.center.y - this.origin.y;
  53942. var z = sphere.center.z - this.origin.z;
  53943. var pyth = (x * x) + (y * y) + (z * z);
  53944. var rr = sphere.radius * sphere.radius;
  53945. if (pyth <= rr) {
  53946. return true;
  53947. }
  53948. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53949. if (dot < 0.0) {
  53950. return false;
  53951. }
  53952. var temp = pyth - (dot * dot);
  53953. return temp <= rr;
  53954. };
  53955. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53956. if (!this._edge1) {
  53957. this._edge1 = BABYLON.Vector3.Zero();
  53958. this._edge2 = BABYLON.Vector3.Zero();
  53959. this._pvec = BABYLON.Vector3.Zero();
  53960. this._tvec = BABYLON.Vector3.Zero();
  53961. this._qvec = BABYLON.Vector3.Zero();
  53962. }
  53963. vertex1.subtractToRef(vertex0, this._edge1);
  53964. vertex2.subtractToRef(vertex0, this._edge2);
  53965. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53966. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53967. if (det === 0) {
  53968. return null;
  53969. }
  53970. var invdet = 1 / det;
  53971. this.origin.subtractToRef(vertex0, this._tvec);
  53972. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53973. if (bu < 0 || bu > 1.0) {
  53974. return null;
  53975. }
  53976. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53977. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53978. if (bv < 0 || bu + bv > 1.0) {
  53979. return null;
  53980. }
  53981. //check if the distance is longer than the predefined length.
  53982. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53983. if (distance > this.length) {
  53984. return null;
  53985. }
  53986. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53987. };
  53988. Ray.prototype.intersectsPlane = function (plane) {
  53989. var distance;
  53990. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53991. if (Math.abs(result1) < 9.99999997475243E-07) {
  53992. return null;
  53993. }
  53994. else {
  53995. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53996. distance = (-plane.d - result2) / result1;
  53997. if (distance < 0.0) {
  53998. if (distance < -9.99999997475243E-07) {
  53999. return null;
  54000. }
  54001. else {
  54002. return 0;
  54003. }
  54004. }
  54005. return distance;
  54006. }
  54007. };
  54008. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54009. var tm = BABYLON.Tmp.Matrix[0];
  54010. mesh.getWorldMatrix().invertToRef(tm);
  54011. if (this._tmpRay) {
  54012. Ray.TransformToRef(this, tm, this._tmpRay);
  54013. }
  54014. else {
  54015. this._tmpRay = Ray.Transform(this, tm);
  54016. }
  54017. return mesh.intersects(this._tmpRay, fastCheck);
  54018. };
  54019. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54020. if (results) {
  54021. results.length = 0;
  54022. }
  54023. else {
  54024. results = [];
  54025. }
  54026. for (var i = 0; i < meshes.length; i++) {
  54027. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54028. if (pickInfo.hit) {
  54029. results.push(pickInfo);
  54030. }
  54031. }
  54032. results.sort(this._comparePickingInfo);
  54033. return results;
  54034. };
  54035. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54036. if (pickingInfoA.distance < pickingInfoB.distance) {
  54037. return -1;
  54038. }
  54039. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54040. return 1;
  54041. }
  54042. else {
  54043. return 0;
  54044. }
  54045. };
  54046. /**
  54047. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54048. * @param sega the first point of the segment to test the intersection against
  54049. * @param segb the second point of the segment to test the intersection against
  54050. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54051. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54052. */
  54053. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54054. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54055. var u = segb.subtract(sega);
  54056. var v = rsegb.subtract(this.origin);
  54057. var w = sega.subtract(this.origin);
  54058. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54059. var b = BABYLON.Vector3.Dot(u, v);
  54060. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54061. var d = BABYLON.Vector3.Dot(u, w);
  54062. var e = BABYLON.Vector3.Dot(v, w);
  54063. var D = a * c - b * b; // always >= 0
  54064. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54065. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54066. // compute the line parameters of the two closest points
  54067. if (D < Ray.smallnum) { // the lines are almost parallel
  54068. sN = 0.0; // force using point P0 on segment S1
  54069. sD = 1.0; // to prevent possible division by 0.0 later
  54070. tN = e;
  54071. tD = c;
  54072. }
  54073. else { // get the closest points on the infinite lines
  54074. sN = (b * e - c * d);
  54075. tN = (a * e - b * d);
  54076. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54077. sN = 0.0;
  54078. tN = e;
  54079. tD = c;
  54080. }
  54081. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54082. sN = sD;
  54083. tN = e + b;
  54084. tD = c;
  54085. }
  54086. }
  54087. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54088. tN = 0.0;
  54089. // recompute sc for this edge
  54090. if (-d < 0.0) {
  54091. sN = 0.0;
  54092. }
  54093. else if (-d > a)
  54094. sN = sD;
  54095. else {
  54096. sN = -d;
  54097. sD = a;
  54098. }
  54099. }
  54100. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54101. tN = tD;
  54102. // recompute sc for this edge
  54103. if ((-d + b) < 0.0) {
  54104. sN = 0;
  54105. }
  54106. else if ((-d + b) > a) {
  54107. sN = sD;
  54108. }
  54109. else {
  54110. sN = (-d + b);
  54111. sD = a;
  54112. }
  54113. }
  54114. // finally do the division to get sc and tc
  54115. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54116. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54117. // get the difference of the two closest points
  54118. var qtc = v.multiplyByFloats(tc, tc, tc);
  54119. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54120. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54121. if (isIntersected) {
  54122. return qtc.length();
  54123. }
  54124. return -1;
  54125. };
  54126. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54127. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54128. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54129. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54130. this.direction.normalize();
  54131. return this;
  54132. };
  54133. // Statics
  54134. Ray.Zero = function () {
  54135. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54136. };
  54137. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54138. var result = Ray.Zero();
  54139. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54140. };
  54141. /**
  54142. * 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
  54143. * transformed to the given world matrix.
  54144. * @param origin The origin point
  54145. * @param end The end point
  54146. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54147. */
  54148. Ray.CreateNewFromTo = function (origin, end, world) {
  54149. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54150. var direction = end.subtract(origin);
  54151. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54152. direction.normalize();
  54153. return Ray.Transform(new Ray(origin, direction, length), world);
  54154. };
  54155. Ray.Transform = function (ray, matrix) {
  54156. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54157. Ray.TransformToRef(ray, matrix, result);
  54158. return result;
  54159. };
  54160. Ray.TransformToRef = function (ray, matrix, result) {
  54161. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54162. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54163. result.length = ray.length;
  54164. var dir = result.direction;
  54165. var len = dir.length();
  54166. if (!(len === 0 || len === 1)) {
  54167. var num = 1.0 / len;
  54168. dir.x *= num;
  54169. dir.y *= num;
  54170. dir.z *= num;
  54171. result.length *= len;
  54172. }
  54173. };
  54174. Ray.smallnum = 0.00000001;
  54175. Ray.rayl = 10e8;
  54176. return Ray;
  54177. }());
  54178. BABYLON.Ray = Ray;
  54179. })(BABYLON || (BABYLON = {}));
  54180. //# sourceMappingURL=babylon.ray.js.map
  54181. var BABYLON;
  54182. (function (BABYLON) {
  54183. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54184. if (boxMin.x > sphereCenter.x + sphereRadius)
  54185. return false;
  54186. if (sphereCenter.x - sphereRadius > boxMax.x)
  54187. return false;
  54188. if (boxMin.y > sphereCenter.y + sphereRadius)
  54189. return false;
  54190. if (sphereCenter.y - sphereRadius > boxMax.y)
  54191. return false;
  54192. if (boxMin.z > sphereCenter.z + sphereRadius)
  54193. return false;
  54194. if (sphereCenter.z - sphereRadius > boxMax.z)
  54195. return false;
  54196. return true;
  54197. };
  54198. var getLowestRoot = (function () {
  54199. var result = { root: 0, found: false };
  54200. return function (a, b, c, maxR) {
  54201. result.root = 0;
  54202. result.found = false;
  54203. var determinant = b * b - 4.0 * a * c;
  54204. if (determinant < 0)
  54205. return result;
  54206. var sqrtD = Math.sqrt(determinant);
  54207. var r1 = (-b - sqrtD) / (2.0 * a);
  54208. var r2 = (-b + sqrtD) / (2.0 * a);
  54209. if (r1 > r2) {
  54210. var temp = r2;
  54211. r2 = r1;
  54212. r1 = temp;
  54213. }
  54214. if (r1 > 0 && r1 < maxR) {
  54215. result.root = r1;
  54216. result.found = true;
  54217. return result;
  54218. }
  54219. if (r2 > 0 && r2 < maxR) {
  54220. result.root = r2;
  54221. result.found = true;
  54222. return result;
  54223. }
  54224. return result;
  54225. };
  54226. })();
  54227. var Collider = /** @class */ (function () {
  54228. function Collider() {
  54229. this._collisionPoint = BABYLON.Vector3.Zero();
  54230. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54231. this._tempVector = BABYLON.Vector3.Zero();
  54232. this._tempVector2 = BABYLON.Vector3.Zero();
  54233. this._tempVector3 = BABYLON.Vector3.Zero();
  54234. this._tempVector4 = BABYLON.Vector3.Zero();
  54235. this._edge = BABYLON.Vector3.Zero();
  54236. this._baseToVertex = BABYLON.Vector3.Zero();
  54237. this._destinationPoint = BABYLON.Vector3.Zero();
  54238. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54239. this._displacementVector = BABYLON.Vector3.Zero();
  54240. this._radius = BABYLON.Vector3.One();
  54241. this._retry = 0;
  54242. this._basePointWorld = BABYLON.Vector3.Zero();
  54243. this._velocityWorld = BABYLON.Vector3.Zero();
  54244. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54245. this._collisionMask = -1;
  54246. }
  54247. Object.defineProperty(Collider.prototype, "collisionMask", {
  54248. get: function () {
  54249. return this._collisionMask;
  54250. },
  54251. set: function (mask) {
  54252. this._collisionMask = !isNaN(mask) ? mask : -1;
  54253. },
  54254. enumerable: true,
  54255. configurable: true
  54256. });
  54257. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54258. /**
  54259. * Gets the plane normal used to compute the sliding response (in local space)
  54260. */
  54261. get: function () {
  54262. return this._slidePlaneNormal;
  54263. },
  54264. enumerable: true,
  54265. configurable: true
  54266. });
  54267. // Methods
  54268. Collider.prototype._initialize = function (source, dir, e) {
  54269. this._velocity = dir;
  54270. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54271. this._basePoint = source;
  54272. source.multiplyToRef(this._radius, this._basePointWorld);
  54273. dir.multiplyToRef(this._radius, this._velocityWorld);
  54274. this._velocityWorldLength = this._velocityWorld.length();
  54275. this._epsilon = e;
  54276. this.collisionFound = false;
  54277. };
  54278. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54279. pa.subtractToRef(point, this._tempVector);
  54280. pb.subtractToRef(point, this._tempVector2);
  54281. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54282. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54283. if (d < 0)
  54284. return false;
  54285. pc.subtractToRef(point, this._tempVector3);
  54286. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54287. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54288. if (d < 0)
  54289. return false;
  54290. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54291. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54292. return d >= 0;
  54293. };
  54294. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54295. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54296. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54297. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54298. return false;
  54299. }
  54300. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54301. return false;
  54302. return true;
  54303. };
  54304. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54305. var t0;
  54306. var embeddedInPlane = false;
  54307. //defensive programming, actually not needed.
  54308. if (!trianglePlaneArray) {
  54309. trianglePlaneArray = [];
  54310. }
  54311. if (!trianglePlaneArray[faceIndex]) {
  54312. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54313. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54314. }
  54315. var trianglePlane = trianglePlaneArray[faceIndex];
  54316. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54317. return;
  54318. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54319. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54320. if (normalDotVelocity == 0) {
  54321. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54322. return;
  54323. embeddedInPlane = true;
  54324. t0 = 0;
  54325. }
  54326. else {
  54327. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54328. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54329. if (t0 > t1) {
  54330. var temp = t1;
  54331. t1 = t0;
  54332. t0 = temp;
  54333. }
  54334. if (t0 > 1.0 || t1 < 0.0)
  54335. return;
  54336. if (t0 < 0)
  54337. t0 = 0;
  54338. if (t0 > 1.0)
  54339. t0 = 1.0;
  54340. }
  54341. this._collisionPoint.copyFromFloats(0, 0, 0);
  54342. var found = false;
  54343. var t = 1.0;
  54344. if (!embeddedInPlane) {
  54345. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54346. this._velocity.scaleToRef(t0, this._tempVector);
  54347. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54348. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54349. found = true;
  54350. t = t0;
  54351. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54352. }
  54353. }
  54354. if (!found) {
  54355. var velocitySquaredLength = this._velocity.lengthSquared();
  54356. var a = velocitySquaredLength;
  54357. this._basePoint.subtractToRef(p1, this._tempVector);
  54358. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54359. var c = this._tempVector.lengthSquared() - 1.0;
  54360. var lowestRoot = getLowestRoot(a, b, c, t);
  54361. if (lowestRoot.found) {
  54362. t = lowestRoot.root;
  54363. found = true;
  54364. this._collisionPoint.copyFrom(p1);
  54365. }
  54366. this._basePoint.subtractToRef(p2, this._tempVector);
  54367. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54368. c = this._tempVector.lengthSquared() - 1.0;
  54369. lowestRoot = getLowestRoot(a, b, c, t);
  54370. if (lowestRoot.found) {
  54371. t = lowestRoot.root;
  54372. found = true;
  54373. this._collisionPoint.copyFrom(p2);
  54374. }
  54375. this._basePoint.subtractToRef(p3, this._tempVector);
  54376. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54377. c = this._tempVector.lengthSquared() - 1.0;
  54378. lowestRoot = getLowestRoot(a, b, c, t);
  54379. if (lowestRoot.found) {
  54380. t = lowestRoot.root;
  54381. found = true;
  54382. this._collisionPoint.copyFrom(p3);
  54383. }
  54384. p2.subtractToRef(p1, this._edge);
  54385. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54386. var edgeSquaredLength = this._edge.lengthSquared();
  54387. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54388. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54389. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54390. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54391. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54392. lowestRoot = getLowestRoot(a, b, c, t);
  54393. if (lowestRoot.found) {
  54394. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54395. if (f >= 0.0 && f <= 1.0) {
  54396. t = lowestRoot.root;
  54397. found = true;
  54398. this._edge.scaleInPlace(f);
  54399. p1.addToRef(this._edge, this._collisionPoint);
  54400. }
  54401. }
  54402. p3.subtractToRef(p2, this._edge);
  54403. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54404. edgeSquaredLength = this._edge.lengthSquared();
  54405. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54406. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54407. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54408. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54409. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54410. lowestRoot = getLowestRoot(a, b, c, t);
  54411. if (lowestRoot.found) {
  54412. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54413. if (f >= 0.0 && f <= 1.0) {
  54414. t = lowestRoot.root;
  54415. found = true;
  54416. this._edge.scaleInPlace(f);
  54417. p2.addToRef(this._edge, this._collisionPoint);
  54418. }
  54419. }
  54420. p1.subtractToRef(p3, this._edge);
  54421. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54422. edgeSquaredLength = this._edge.lengthSquared();
  54423. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54424. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54425. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54426. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54427. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54428. lowestRoot = getLowestRoot(a, b, c, t);
  54429. if (lowestRoot.found) {
  54430. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54431. if (f >= 0.0 && f <= 1.0) {
  54432. t = lowestRoot.root;
  54433. found = true;
  54434. this._edge.scaleInPlace(f);
  54435. p3.addToRef(this._edge, this._collisionPoint);
  54436. }
  54437. }
  54438. }
  54439. if (found) {
  54440. var distToCollision = t * this._velocity.length();
  54441. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54442. if (!this.intersectionPoint) {
  54443. this.intersectionPoint = this._collisionPoint.clone();
  54444. }
  54445. else {
  54446. this.intersectionPoint.copyFrom(this._collisionPoint);
  54447. }
  54448. this._nearestDistance = distToCollision;
  54449. this.collisionFound = true;
  54450. }
  54451. }
  54452. };
  54453. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54454. for (var i = indexStart; i < indexEnd; i += 3) {
  54455. var p1 = pts[indices[i] - decal];
  54456. var p2 = pts[indices[i + 1] - decal];
  54457. var p3 = pts[indices[i + 2] - decal];
  54458. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54459. }
  54460. };
  54461. Collider.prototype._getResponse = function (pos, vel) {
  54462. pos.addToRef(vel, this._destinationPoint);
  54463. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54464. this._basePoint.addToRef(vel, pos);
  54465. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54466. this._slidePlaneNormal.normalize();
  54467. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54468. pos.addInPlace(this._displacementVector);
  54469. this.intersectionPoint.addInPlace(this._displacementVector);
  54470. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54471. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54472. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54473. };
  54474. return Collider;
  54475. }());
  54476. BABYLON.Collider = Collider;
  54477. })(BABYLON || (BABYLON = {}));
  54478. //# sourceMappingURL=babylon.collider.js.map
  54479. var BABYLON;
  54480. (function (BABYLON) {
  54481. //WebWorker code will be inserted to this variable.
  54482. BABYLON.CollisionWorker = "";
  54483. /** Defines supported task for worker process */
  54484. var WorkerTaskType;
  54485. (function (WorkerTaskType) {
  54486. /** Initialization */
  54487. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54488. /** Update of geometry */
  54489. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54490. /** Evaluate collision */
  54491. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54492. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54493. /** Defines kind of replies returned by worker */
  54494. var WorkerReplyType;
  54495. (function (WorkerReplyType) {
  54496. /** Success */
  54497. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54498. /** Unkown error */
  54499. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54500. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54501. var CollisionCoordinatorWorker = /** @class */ (function () {
  54502. function CollisionCoordinatorWorker() {
  54503. var _this = this;
  54504. this._scaledPosition = BABYLON.Vector3.Zero();
  54505. this._scaledVelocity = BABYLON.Vector3.Zero();
  54506. this.onMeshUpdated = function (transformNode) {
  54507. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54508. };
  54509. this.onGeometryUpdated = function (geometry) {
  54510. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54511. };
  54512. this._afterRender = function () {
  54513. if (!_this._init)
  54514. return;
  54515. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54516. return;
  54517. }
  54518. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54519. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54520. if (_this._runningUpdated > 4) {
  54521. return;
  54522. }
  54523. ++_this._runningUpdated;
  54524. var payload = {
  54525. updatedMeshes: _this._addUpdateMeshesList,
  54526. updatedGeometries: _this._addUpdateGeometriesList,
  54527. removedGeometries: _this._toRemoveGeometryArray,
  54528. removedMeshes: _this._toRemoveMeshesArray
  54529. };
  54530. var message = {
  54531. payload: payload,
  54532. taskType: WorkerTaskType.UPDATE
  54533. };
  54534. var serializable = [];
  54535. for (var id in payload.updatedGeometries) {
  54536. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54537. //prepare transferables
  54538. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54539. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54540. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54541. }
  54542. }
  54543. _this._worker.postMessage(message, serializable);
  54544. _this._addUpdateMeshesList = {};
  54545. _this._addUpdateGeometriesList = {};
  54546. _this._toRemoveGeometryArray = [];
  54547. _this._toRemoveMeshesArray = [];
  54548. };
  54549. this._onMessageFromWorker = function (e) {
  54550. var returnData = e.data;
  54551. if (returnData.error != WorkerReplyType.SUCCESS) {
  54552. //TODO what errors can be returned from the worker?
  54553. BABYLON.Tools.Warn("error returned from worker!");
  54554. return;
  54555. }
  54556. switch (returnData.taskType) {
  54557. case WorkerTaskType.INIT:
  54558. _this._init = true;
  54559. //Update the worked with ALL of the scene's current state
  54560. _this._scene.meshes.forEach(function (mesh) {
  54561. _this.onMeshAdded(mesh);
  54562. });
  54563. _this._scene.getGeometries().forEach(function (geometry) {
  54564. _this.onGeometryAdded(geometry);
  54565. });
  54566. break;
  54567. case WorkerTaskType.UPDATE:
  54568. _this._runningUpdated--;
  54569. break;
  54570. case WorkerTaskType.COLLIDE:
  54571. var returnPayload = returnData.payload;
  54572. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54573. return;
  54574. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54575. if (callback) {
  54576. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54577. if (mesh) {
  54578. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54579. }
  54580. }
  54581. //cleanup
  54582. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54583. break;
  54584. }
  54585. };
  54586. this._collisionsCallbackArray = [];
  54587. this._init = false;
  54588. this._runningUpdated = 0;
  54589. this._addUpdateMeshesList = {};
  54590. this._addUpdateGeometriesList = {};
  54591. this._toRemoveGeometryArray = [];
  54592. this._toRemoveMeshesArray = [];
  54593. }
  54594. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54595. if (!this._init)
  54596. return;
  54597. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54598. return;
  54599. position.divideToRef(collider._radius, this._scaledPosition);
  54600. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54601. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54602. var payload = {
  54603. collider: {
  54604. position: this._scaledPosition.asArray(),
  54605. velocity: this._scaledVelocity.asArray(),
  54606. radius: collider._radius.asArray()
  54607. },
  54608. collisionId: collisionIndex,
  54609. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54610. maximumRetry: maximumRetry
  54611. };
  54612. var message = {
  54613. payload: payload,
  54614. taskType: WorkerTaskType.COLLIDE
  54615. };
  54616. this._worker.postMessage(message);
  54617. };
  54618. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54619. this._scene = scene;
  54620. this._scene.registerAfterRender(this._afterRender);
  54621. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54622. this._worker = new Worker(workerUrl);
  54623. this._worker.onmessage = this._onMessageFromWorker;
  54624. var message = {
  54625. payload: {},
  54626. taskType: WorkerTaskType.INIT
  54627. };
  54628. this._worker.postMessage(message);
  54629. };
  54630. CollisionCoordinatorWorker.prototype.destroy = function () {
  54631. this._scene.unregisterAfterRender(this._afterRender);
  54632. this._worker.terminate();
  54633. };
  54634. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54635. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54636. this.onMeshUpdated(mesh);
  54637. };
  54638. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54639. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54640. };
  54641. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54642. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54643. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54644. this.onGeometryUpdated(geometry);
  54645. };
  54646. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54647. this._toRemoveGeometryArray.push(geometry.id);
  54648. };
  54649. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54650. var submeshes = [];
  54651. if (mesh.subMeshes) {
  54652. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54653. var boundingInfo = sm.getBoundingInfo();
  54654. return {
  54655. position: idx,
  54656. verticesStart: sm.verticesStart,
  54657. verticesCount: sm.verticesCount,
  54658. indexStart: sm.indexStart,
  54659. indexCount: sm.indexCount,
  54660. hasMaterial: !!sm.getMaterial(),
  54661. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54662. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54663. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54664. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54665. };
  54666. });
  54667. }
  54668. var geometryId = null;
  54669. if (mesh instanceof BABYLON.Mesh) {
  54670. var geometry = mesh.geometry;
  54671. geometryId = geometry ? geometry.id : null;
  54672. }
  54673. else if (mesh instanceof BABYLON.InstancedMesh) {
  54674. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54675. geometryId = geometry ? geometry.id : null;
  54676. }
  54677. var boundingInfo = mesh.getBoundingInfo();
  54678. return {
  54679. uniqueId: mesh.uniqueId,
  54680. id: mesh.id,
  54681. name: mesh.name,
  54682. geometryId: geometryId,
  54683. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54684. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54685. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54686. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54687. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54688. subMeshes: submeshes,
  54689. checkCollisions: mesh.checkCollisions
  54690. };
  54691. };
  54692. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54693. return {
  54694. id: geometry.id,
  54695. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54696. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54697. indices: new Uint32Array(geometry.getIndices() || []),
  54698. };
  54699. };
  54700. return CollisionCoordinatorWorker;
  54701. }());
  54702. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54703. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54704. function CollisionCoordinatorLegacy() {
  54705. this._scaledPosition = BABYLON.Vector3.Zero();
  54706. this._scaledVelocity = BABYLON.Vector3.Zero();
  54707. this._finalPosition = BABYLON.Vector3.Zero();
  54708. }
  54709. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54710. position.divideToRef(collider._radius, this._scaledPosition);
  54711. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54712. collider.collidedMesh = null;
  54713. collider._retry = 0;
  54714. collider._initialVelocity = this._scaledVelocity;
  54715. collider._initialPosition = this._scaledPosition;
  54716. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54717. this._finalPosition.multiplyInPlace(collider._radius);
  54718. //run the callback
  54719. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54720. };
  54721. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54722. this._scene = scene;
  54723. };
  54724. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54725. //Legacy need no destruction method.
  54726. };
  54727. //No update in legacy mode
  54728. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54729. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54730. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54731. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54732. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54733. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54734. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54735. if (excludedMesh === void 0) { excludedMesh = null; }
  54736. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54737. if (collider._retry >= maximumRetry) {
  54738. finalPosition.copyFrom(position);
  54739. return;
  54740. }
  54741. // Check if this is a mesh else camera or -1
  54742. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54743. collider._initialize(position, velocity, closeDistance);
  54744. // Check all meshes
  54745. for (var index = 0; index < this._scene.meshes.length; index++) {
  54746. var mesh = this._scene.meshes[index];
  54747. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54748. mesh._checkCollision(collider);
  54749. }
  54750. }
  54751. if (!collider.collisionFound) {
  54752. position.addToRef(velocity, finalPosition);
  54753. return;
  54754. }
  54755. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54756. collider._getResponse(position, velocity);
  54757. }
  54758. if (velocity.length() <= closeDistance) {
  54759. finalPosition.copyFrom(position);
  54760. return;
  54761. }
  54762. collider._retry++;
  54763. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54764. };
  54765. return CollisionCoordinatorLegacy;
  54766. }());
  54767. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54768. })(BABYLON || (BABYLON = {}));
  54769. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54770. var BABYLON;
  54771. (function (BABYLON) {
  54772. /**
  54773. * A particle represents one of the element emitted by a particle system.
  54774. * This is mainly define by its coordinates, direction, velocity and age.
  54775. */
  54776. var Particle = /** @class */ (function () {
  54777. /**
  54778. * Creates a new instance Particle
  54779. * @param particleSystem the particle system the particle belongs to
  54780. */
  54781. function Particle(
  54782. /**
  54783. * particleSystem the particle system the particle belongs to.
  54784. */
  54785. particleSystem) {
  54786. this.particleSystem = particleSystem;
  54787. /**
  54788. * The world position of the particle in the scene.
  54789. */
  54790. this.position = BABYLON.Vector3.Zero();
  54791. /**
  54792. * The world direction of the particle in the scene.
  54793. */
  54794. this.direction = BABYLON.Vector3.Zero();
  54795. /**
  54796. * The color of the particle.
  54797. */
  54798. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54799. /**
  54800. * The color change of the particle per step.
  54801. */
  54802. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54803. /**
  54804. * Defines how long will the life of the particle be.
  54805. */
  54806. this.lifeTime = 1.0;
  54807. /**
  54808. * The current age of the particle.
  54809. */
  54810. this.age = 0;
  54811. /**
  54812. * The current size of the particle.
  54813. */
  54814. this.size = 0;
  54815. /**
  54816. * The current scale of the particle.
  54817. */
  54818. this.scale = new BABYLON.Vector2(1, 1);
  54819. /**
  54820. * The current angle of the particle.
  54821. */
  54822. this.angle = 0;
  54823. /**
  54824. * Defines how fast is the angle changing.
  54825. */
  54826. this.angularSpeed = 0;
  54827. /**
  54828. * Defines the cell index used by the particle to be rendered from a sprite.
  54829. */
  54830. this.cellIndex = 0;
  54831. this._currentFrameCounter = 0;
  54832. if (!this.particleSystem.isAnimationSheetEnabled) {
  54833. return;
  54834. }
  54835. this.updateCellInfoFromSystem();
  54836. }
  54837. Particle.prototype.updateCellInfoFromSystem = function () {
  54838. this.cellIndex = this.particleSystem.startSpriteCellID;
  54839. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54840. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54841. }
  54842. else {
  54843. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54844. }
  54845. };
  54846. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54847. // (ageOffset / scaledUpdateSpeed) / available cells
  54848. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54849. this._currentFrameCounter += scaledUpdateSpeed;
  54850. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54851. this._currentFrameCounter = 0;
  54852. this.cellIndex++;
  54853. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54854. this.cellIndex = this.particleSystem.endSpriteCellID;
  54855. }
  54856. }
  54857. };
  54858. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54859. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54860. this.cellIndex++;
  54861. this._currentFrameCounter = 0;
  54862. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54863. if (this.particleSystem.spriteCellLoop) {
  54864. this.cellIndex = this.particleSystem.startSpriteCellID;
  54865. }
  54866. else {
  54867. this.cellIndex = this.particleSystem.endSpriteCellID;
  54868. }
  54869. }
  54870. }
  54871. else {
  54872. this._currentFrameCounter++;
  54873. }
  54874. };
  54875. /**
  54876. * Copy the properties of particle to another one.
  54877. * @param other the particle to copy the information to.
  54878. */
  54879. Particle.prototype.copyTo = function (other) {
  54880. other.position.copyFrom(this.position);
  54881. if (this._initialDirection) {
  54882. if (other._initialDirection) {
  54883. other._initialDirection.copyFrom(this._initialDirection);
  54884. }
  54885. else {
  54886. other._initialDirection = this._initialDirection.clone();
  54887. }
  54888. }
  54889. else {
  54890. other._initialDirection = null;
  54891. }
  54892. other.direction.copyFrom(this.direction);
  54893. other.color.copyFrom(this.color);
  54894. other.colorStep.copyFrom(this.colorStep);
  54895. other.lifeTime = this.lifeTime;
  54896. other.age = this.age;
  54897. other.size = this.size;
  54898. other.scale.copyFrom(this.scale);
  54899. other.angle = this.angle;
  54900. other.angularSpeed = this.angularSpeed;
  54901. other.particleSystem = this.particleSystem;
  54902. other.cellIndex = this.cellIndex;
  54903. };
  54904. return Particle;
  54905. }());
  54906. BABYLON.Particle = Particle;
  54907. })(BABYLON || (BABYLON = {}));
  54908. //# sourceMappingURL=babylon.particle.js.map
  54909. var BABYLON;
  54910. (function (BABYLON) {
  54911. /**
  54912. * This represents a particle system in Babylon.
  54913. * 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.
  54914. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54915. * @example https://doc.babylonjs.com/babylon101/particles
  54916. */
  54917. var ParticleSystem = /** @class */ (function () {
  54918. /**
  54919. * Instantiates a particle system.
  54920. * 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.
  54921. * @param name The name of the particle system
  54922. * @param capacity The max number of particles alive at the same time
  54923. * @param scene The scene the particle system belongs to
  54924. * @param customEffect a custom effect used to change the way particles are rendered by default
  54925. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54926. * @param epsilon Offset used to render the particles
  54927. */
  54928. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54929. if (customEffect === void 0) { customEffect = null; }
  54930. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54931. if (epsilon === void 0) { epsilon = 0.01; }
  54932. var _this = this;
  54933. /**
  54934. * List of animations used by the particle system.
  54935. */
  54936. this.animations = [];
  54937. /**
  54938. * The rendering group used by the Particle system to chose when to render.
  54939. */
  54940. this.renderingGroupId = 0;
  54941. /**
  54942. * The emitter represents the Mesh or position we are attaching the particle system to.
  54943. */
  54944. this.emitter = null;
  54945. /**
  54946. * The maximum number of particles to emit per frame
  54947. */
  54948. this.emitRate = 10;
  54949. /**
  54950. * If you want to launch only a few particles at once, that can be done, as well.
  54951. */
  54952. this.manualEmitCount = -1;
  54953. /**
  54954. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54955. */
  54956. this.updateSpeed = 0.01;
  54957. /**
  54958. * The amount of time the particle system is running (depends of the overall update speed).
  54959. */
  54960. this.targetStopDuration = 0;
  54961. /**
  54962. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54963. */
  54964. this.disposeOnStop = false;
  54965. /**
  54966. * Minimum power of emitting particles.
  54967. */
  54968. this.minEmitPower = 1;
  54969. /**
  54970. * Maximum power of emitting particles.
  54971. */
  54972. this.maxEmitPower = 1;
  54973. /**
  54974. * Minimum life time of emitting particles.
  54975. */
  54976. this.minLifeTime = 1;
  54977. /**
  54978. * Maximum life time of emitting particles.
  54979. */
  54980. this.maxLifeTime = 1;
  54981. /**
  54982. * Minimum Size of emitting particles.
  54983. */
  54984. this.minSize = 1;
  54985. /**
  54986. * Maximum Size of emitting particles.
  54987. */
  54988. this.maxSize = 1;
  54989. /**
  54990. * Minimum scale of emitting particles on X axis.
  54991. */
  54992. this.minScaleX = 1;
  54993. /**
  54994. * Maximum scale of emitting particles on X axis.
  54995. */
  54996. this.maxScaleX = 1;
  54997. /**
  54998. * Minimum scale of emitting particles on Y axis.
  54999. */
  55000. this.minScaleY = 1;
  55001. /**
  55002. * Maximum scale of emitting particles on Y axis.
  55003. */
  55004. this.maxScaleY = 1;
  55005. /**
  55006. * Gets or sets the minimal initial rotation in radians.
  55007. */
  55008. this.minInitialRotation = 0;
  55009. /**
  55010. * Gets or sets the maximal initial rotation in radians.
  55011. */
  55012. this.maxInitialRotation = 0;
  55013. /**
  55014. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55015. */
  55016. this.minAngularSpeed = 0;
  55017. /**
  55018. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55019. */
  55020. this.maxAngularSpeed = 0;
  55021. /**
  55022. * The layer mask we are rendering the particles through.
  55023. */
  55024. this.layerMask = 0x0FFFFFFF;
  55025. /**
  55026. * This can help using your own shader to render the particle system.
  55027. * The according effect will be created
  55028. */
  55029. this.customShader = null;
  55030. /**
  55031. * By default particle system starts as soon as they are created. This prevents the
  55032. * automatic start to happen and let you decide when to start emitting particles.
  55033. */
  55034. this.preventAutoStart = false;
  55035. /**
  55036. * Callback triggered when the particle animation is ending.
  55037. */
  55038. this.onAnimationEnd = null;
  55039. /**
  55040. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55041. */
  55042. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55043. /**
  55044. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55045. * to override the particles.
  55046. */
  55047. this.forceDepthWrite = false;
  55048. /**
  55049. * You can use gravity if you want to give an orientation to your particles.
  55050. */
  55051. this.gravity = BABYLON.Vector3.Zero();
  55052. this._colorGradients = null;
  55053. this._sizeGradients = null;
  55054. /**
  55055. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55056. */
  55057. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55058. /**
  55059. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55060. */
  55061. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55062. /**
  55063. * Color the particle will have at the end of its lifetime
  55064. */
  55065. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55066. /**
  55067. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55068. */
  55069. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55070. /**
  55071. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55072. */
  55073. this.spriteCellLoop = true;
  55074. /**
  55075. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55076. */
  55077. this.spriteCellChangeSpeed = 0;
  55078. /**
  55079. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55080. */
  55081. this.startSpriteCellID = 0;
  55082. /**
  55083. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55084. */
  55085. this.endSpriteCellID = 0;
  55086. /**
  55087. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55088. */
  55089. this.spriteCellWidth = 0;
  55090. /**
  55091. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55092. */
  55093. this.spriteCellHeight = 0;
  55094. /** 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 */
  55095. this.preWarmCycles = 0;
  55096. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55097. this.preWarmStepOffset = 1;
  55098. /**
  55099. * An event triggered when the system is disposed
  55100. */
  55101. this.onDisposeObservable = new BABYLON.Observable();
  55102. this._particles = new Array();
  55103. this._stockParticles = new Array();
  55104. this._newPartsExcess = 0;
  55105. this._vertexBuffers = {};
  55106. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55107. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55108. this._scaledDirection = BABYLON.Vector3.Zero();
  55109. this._scaledGravity = BABYLON.Vector3.Zero();
  55110. this._currentRenderId = -1;
  55111. this._useInstancing = false;
  55112. this._started = false;
  55113. this._stopped = false;
  55114. this._actualFrame = 0;
  55115. this._isBillboardBased = true;
  55116. // start of sub system methods
  55117. /**
  55118. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55119. * Its lifetime will start back at 0.
  55120. */
  55121. this.recycleParticle = function (particle) {
  55122. var lastParticle = _this._particles.pop();
  55123. if (lastParticle !== particle) {
  55124. lastParticle.copyTo(particle);
  55125. }
  55126. _this._stockParticles.push(lastParticle);
  55127. };
  55128. this._createParticle = function () {
  55129. var particle;
  55130. if (_this._stockParticles.length !== 0) {
  55131. particle = _this._stockParticles.pop();
  55132. particle.age = 0;
  55133. particle.cellIndex = _this.startSpriteCellID;
  55134. }
  55135. else {
  55136. particle = new BABYLON.Particle(_this);
  55137. }
  55138. return particle;
  55139. };
  55140. this._emitFromParticle = function (particle) {
  55141. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55142. return;
  55143. }
  55144. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55145. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55146. subSystem._rootParticleSystem = _this;
  55147. _this.activeSubSystems.push(subSystem);
  55148. subSystem.start();
  55149. };
  55150. this.id = name;
  55151. this.name = name;
  55152. this._capacity = capacity;
  55153. this._epsilon = epsilon;
  55154. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55155. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55156. this._customEffect = customEffect;
  55157. scene.particleSystems.push(this);
  55158. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55159. this._createIndexBuffer();
  55160. this._createVertexBuffers();
  55161. // Default emitter type
  55162. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55163. this.updateFunction = function (particles) {
  55164. for (var index = 0; index < particles.length; index++) {
  55165. var particle = particles[index];
  55166. particle.age += _this._scaledUpdateSpeed;
  55167. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55168. _this._emitFromParticle(particle);
  55169. _this.recycleParticle(particle);
  55170. index--;
  55171. continue;
  55172. }
  55173. else {
  55174. var ratio = particle.age / particle.lifeTime;
  55175. // Color
  55176. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55177. var color1 = BABYLON.Tmp.Color4[0];
  55178. var color2 = BABYLON.Tmp.Color4[1];
  55179. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55180. currentGradient.getColorToRef(color1);
  55181. nextGradient.getColorToRef(color2);
  55182. BABYLON.Color4.LerpToRef(color1, color2, scale, particle.color);
  55183. });
  55184. }
  55185. else {
  55186. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55187. particle.color.addInPlace(_this._scaledColorStep);
  55188. if (particle.color.a < 0) {
  55189. particle.color.a = 0;
  55190. }
  55191. }
  55192. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55193. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55194. particle.position.addInPlace(_this._scaledDirection);
  55195. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55196. particle.direction.addInPlace(_this._scaledGravity);
  55197. // Gradient
  55198. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55199. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55200. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55201. });
  55202. }
  55203. if (_this._isAnimationSheetEnabled) {
  55204. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55205. }
  55206. }
  55207. }
  55208. };
  55209. }
  55210. /**
  55211. * Gets the current list of color gradients.
  55212. * You must use addColorGradient and removeColorGradient to udpate this list
  55213. * @returns the list of color gradients
  55214. */
  55215. ParticleSystem.prototype.getColorGradients = function () {
  55216. return this._colorGradients;
  55217. };
  55218. /**
  55219. * Gets the current list of size gradients.
  55220. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55221. * @returns the list of size gradients
  55222. */
  55223. ParticleSystem.prototype.getSizeGradients = function () {
  55224. return this._sizeGradients;
  55225. };
  55226. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55227. /**
  55228. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55229. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55230. */
  55231. get: function () {
  55232. if (this.particleEmitterType.direction1) {
  55233. return this.particleEmitterType.direction1;
  55234. }
  55235. return BABYLON.Vector3.Zero();
  55236. },
  55237. set: function (value) {
  55238. if (this.particleEmitterType.direction1) {
  55239. this.particleEmitterType.direction1 = value;
  55240. }
  55241. },
  55242. enumerable: true,
  55243. configurable: true
  55244. });
  55245. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55246. /**
  55247. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55248. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55249. */
  55250. get: function () {
  55251. if (this.particleEmitterType.direction2) {
  55252. return this.particleEmitterType.direction2;
  55253. }
  55254. return BABYLON.Vector3.Zero();
  55255. },
  55256. set: function (value) {
  55257. if (this.particleEmitterType.direction2) {
  55258. this.particleEmitterType.direction2 = value;
  55259. }
  55260. },
  55261. enumerable: true,
  55262. configurable: true
  55263. });
  55264. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55265. /**
  55266. * 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.
  55267. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55268. */
  55269. get: function () {
  55270. if (this.particleEmitterType.minEmitBox) {
  55271. return this.particleEmitterType.minEmitBox;
  55272. }
  55273. return BABYLON.Vector3.Zero();
  55274. },
  55275. set: function (value) {
  55276. if (this.particleEmitterType.minEmitBox) {
  55277. this.particleEmitterType.minEmitBox = value;
  55278. }
  55279. },
  55280. enumerable: true,
  55281. configurable: true
  55282. });
  55283. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55284. /**
  55285. * 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.
  55286. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55287. */
  55288. get: function () {
  55289. if (this.particleEmitterType.maxEmitBox) {
  55290. return this.particleEmitterType.maxEmitBox;
  55291. }
  55292. return BABYLON.Vector3.Zero();
  55293. },
  55294. set: function (value) {
  55295. if (this.particleEmitterType.maxEmitBox) {
  55296. this.particleEmitterType.maxEmitBox = value;
  55297. }
  55298. },
  55299. enumerable: true,
  55300. configurable: true
  55301. });
  55302. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55303. /**
  55304. * Sets a callback that will be triggered when the system is disposed
  55305. */
  55306. set: function (callback) {
  55307. if (this._onDisposeObserver) {
  55308. this.onDisposeObservable.remove(this._onDisposeObserver);
  55309. }
  55310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55311. },
  55312. enumerable: true,
  55313. configurable: true
  55314. });
  55315. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55316. /**
  55317. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55318. */
  55319. get: function () {
  55320. return this._isAnimationSheetEnabled;
  55321. },
  55322. enumerable: true,
  55323. configurable: true
  55324. });
  55325. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55326. /**
  55327. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55328. */
  55329. get: function () {
  55330. return this._isBillboardBased;
  55331. },
  55332. set: function (value) {
  55333. if (this._isBillboardBased === value) {
  55334. return;
  55335. }
  55336. this._isBillboardBased = value;
  55337. this._resetEffect();
  55338. },
  55339. enumerable: true,
  55340. configurable: true
  55341. });
  55342. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55343. //end of Sub-emitter
  55344. /**
  55345. * Gets the current list of active particles
  55346. */
  55347. get: function () {
  55348. return this._particles;
  55349. },
  55350. enumerable: true,
  55351. configurable: true
  55352. });
  55353. /**
  55354. * Returns the string "ParticleSystem"
  55355. * @returns a string containing the class name
  55356. */
  55357. ParticleSystem.prototype.getClassName = function () {
  55358. return "ParticleSystem";
  55359. };
  55360. /**
  55361. * Adds a new size gradient
  55362. * @param gradient defines the gradient to use (between 0 and 1)
  55363. * @param factor defines the size factor to affect to the specified gradient
  55364. */
  55365. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55366. if (!this._sizeGradients) {
  55367. this._sizeGradients = [];
  55368. }
  55369. var sizeGradient = new BABYLON.FactorGradient();
  55370. sizeGradient.gradient = gradient;
  55371. sizeGradient.factor = factor;
  55372. this._sizeGradients.push(sizeGradient);
  55373. this._sizeGradients.sort(function (a, b) {
  55374. if (a.gradient < b.gradient) {
  55375. return -1;
  55376. }
  55377. else if (a.gradient > b.gradient) {
  55378. return 1;
  55379. }
  55380. return 0;
  55381. });
  55382. return this;
  55383. };
  55384. /**
  55385. * Remove a specific size gradient
  55386. * @param gradient defines the gradient to remove
  55387. */
  55388. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55389. if (!this._sizeGradients) {
  55390. return this;
  55391. }
  55392. var index = 0;
  55393. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55394. var sizeGradient = _a[_i];
  55395. if (sizeGradient.gradient === gradient) {
  55396. this._sizeGradients.splice(index, 1);
  55397. break;
  55398. }
  55399. index++;
  55400. }
  55401. return this;
  55402. };
  55403. /**
  55404. * Adds a new color gradient
  55405. * @param gradient defines the gradient to use (between 0 and 1)
  55406. * @param color defines the color to affect to the specified gradient
  55407. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55408. */
  55409. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55410. if (!this._colorGradients) {
  55411. this._colorGradients = [];
  55412. }
  55413. var colorGradient = new BABYLON.ColorGradient();
  55414. colorGradient.gradient = gradient;
  55415. colorGradient.color1 = color;
  55416. colorGradient.color2 = color2;
  55417. this._colorGradients.push(colorGradient);
  55418. this._colorGradients.sort(function (a, b) {
  55419. if (a.gradient < b.gradient) {
  55420. return -1;
  55421. }
  55422. else if (a.gradient > b.gradient) {
  55423. return 1;
  55424. }
  55425. return 0;
  55426. });
  55427. return this;
  55428. };
  55429. /**
  55430. * Remove a specific color gradient
  55431. * @param gradient defines the gradient to remove
  55432. */
  55433. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55434. if (!this._colorGradients) {
  55435. return this;
  55436. }
  55437. var index = 0;
  55438. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55439. var colorGradient = _a[_i];
  55440. if (colorGradient.gradient === gradient) {
  55441. this._colorGradients.splice(index, 1);
  55442. break;
  55443. }
  55444. index++;
  55445. }
  55446. return this;
  55447. };
  55448. ParticleSystem.prototype._resetEffect = function () {
  55449. if (this._vertexBuffer) {
  55450. this._vertexBuffer.dispose();
  55451. this._vertexBuffer = null;
  55452. }
  55453. if (this._spriteBuffer) {
  55454. this._spriteBuffer.dispose();
  55455. this._spriteBuffer = null;
  55456. }
  55457. this._createVertexBuffers();
  55458. };
  55459. ParticleSystem.prototype._createVertexBuffers = function () {
  55460. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55461. if (this._isAnimationSheetEnabled) {
  55462. this._vertexBufferSize += 1;
  55463. }
  55464. if (!this._isBillboardBased) {
  55465. this._vertexBufferSize += 3;
  55466. }
  55467. var engine = this._scene.getEngine();
  55468. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55469. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55470. var dataOffset = 0;
  55471. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55473. dataOffset += 3;
  55474. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55475. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55476. dataOffset += 4;
  55477. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55478. this._vertexBuffers["angle"] = options;
  55479. dataOffset += 1;
  55480. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55481. this._vertexBuffers["size"] = size;
  55482. dataOffset += 2;
  55483. if (this._isAnimationSheetEnabled) {
  55484. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55485. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55486. dataOffset += 1;
  55487. }
  55488. if (!this._isBillboardBased) {
  55489. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55490. this._vertexBuffers["direction"] = directionBuffer;
  55491. dataOffset += 3;
  55492. }
  55493. var offsets;
  55494. if (this._useInstancing) {
  55495. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55496. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55497. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55498. }
  55499. else {
  55500. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55501. dataOffset += 2;
  55502. }
  55503. this._vertexBuffers["offset"] = offsets;
  55504. };
  55505. ParticleSystem.prototype._createIndexBuffer = function () {
  55506. if (this._useInstancing) {
  55507. return;
  55508. }
  55509. var indices = [];
  55510. var index = 0;
  55511. for (var count = 0; count < this._capacity; count++) {
  55512. indices.push(index);
  55513. indices.push(index + 1);
  55514. indices.push(index + 2);
  55515. indices.push(index);
  55516. indices.push(index + 2);
  55517. indices.push(index + 3);
  55518. index += 4;
  55519. }
  55520. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55521. };
  55522. /**
  55523. * Gets the maximum number of particles active at the same time.
  55524. * @returns The max number of active particles.
  55525. */
  55526. ParticleSystem.prototype.getCapacity = function () {
  55527. return this._capacity;
  55528. };
  55529. /**
  55530. * Gets Wether there are still active particles in the system.
  55531. * @returns True if it is alive, otherwise false.
  55532. */
  55533. ParticleSystem.prototype.isAlive = function () {
  55534. return this._alive;
  55535. };
  55536. /**
  55537. * Gets Wether the system has been started.
  55538. * @returns True if it has been started, otherwise false.
  55539. */
  55540. ParticleSystem.prototype.isStarted = function () {
  55541. return this._started;
  55542. };
  55543. /**
  55544. * Starts the particle system and begins to emit.
  55545. */
  55546. ParticleSystem.prototype.start = function () {
  55547. this._started = true;
  55548. this._stopped = false;
  55549. this._actualFrame = 0;
  55550. if (this.subEmitters && this.subEmitters.length != 0) {
  55551. this.activeSubSystems = new Array();
  55552. }
  55553. if (this.preWarmCycles) {
  55554. for (var index = 0; index < this.preWarmCycles; index++) {
  55555. this.animate(true);
  55556. }
  55557. }
  55558. };
  55559. /**
  55560. * Stops the particle system.
  55561. * @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.
  55562. */
  55563. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55564. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55565. this._stopped = true;
  55566. if (stopSubEmitters) {
  55567. this._stopSubEmitters();
  55568. }
  55569. };
  55570. // animation sheet
  55571. /**
  55572. * Remove all active particles
  55573. */
  55574. ParticleSystem.prototype.reset = function () {
  55575. this._stockParticles = [];
  55576. this._particles = [];
  55577. };
  55578. /**
  55579. * @hidden (for internal use only)
  55580. */
  55581. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55582. var offset = index * this._vertexBufferSize;
  55583. this._vertexData[offset++] = particle.position.x;
  55584. this._vertexData[offset++] = particle.position.y;
  55585. this._vertexData[offset++] = particle.position.z;
  55586. this._vertexData[offset++] = particle.color.r;
  55587. this._vertexData[offset++] = particle.color.g;
  55588. this._vertexData[offset++] = particle.color.b;
  55589. this._vertexData[offset++] = particle.color.a;
  55590. this._vertexData[offset++] = particle.angle;
  55591. this._vertexData[offset++] = particle.scale.x * particle.size;
  55592. this._vertexData[offset++] = particle.scale.y * particle.size;
  55593. if (this._isAnimationSheetEnabled) {
  55594. this._vertexData[offset++] = particle.cellIndex;
  55595. }
  55596. if (!this._isBillboardBased) {
  55597. if (particle._initialDirection) {
  55598. this._vertexData[offset++] = particle._initialDirection.x;
  55599. this._vertexData[offset++] = particle._initialDirection.y;
  55600. this._vertexData[offset++] = particle._initialDirection.z;
  55601. }
  55602. else {
  55603. this._vertexData[offset++] = particle.direction.x;
  55604. this._vertexData[offset++] = particle.direction.y;
  55605. this._vertexData[offset++] = particle.direction.z;
  55606. }
  55607. }
  55608. if (!this._useInstancing) {
  55609. if (this._isAnimationSheetEnabled) {
  55610. if (offsetX === 0)
  55611. offsetX = this._epsilon;
  55612. else if (offsetX === 1)
  55613. offsetX = 1 - this._epsilon;
  55614. if (offsetY === 0)
  55615. offsetY = this._epsilon;
  55616. else if (offsetY === 1)
  55617. offsetY = 1 - this._epsilon;
  55618. }
  55619. this._vertexData[offset++] = offsetX;
  55620. this._vertexData[offset++] = offsetY;
  55621. }
  55622. };
  55623. ParticleSystem.prototype._stopSubEmitters = function () {
  55624. if (!this.activeSubSystems) {
  55625. return;
  55626. }
  55627. this.activeSubSystems.forEach(function (subSystem) {
  55628. subSystem.stop(true);
  55629. });
  55630. this.activeSubSystems = new Array();
  55631. };
  55632. ParticleSystem.prototype._removeFromRoot = function () {
  55633. if (!this._rootParticleSystem) {
  55634. return;
  55635. }
  55636. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55637. if (index !== -1) {
  55638. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55639. }
  55640. };
  55641. // end of sub system methods
  55642. ParticleSystem.prototype._update = function (newParticles) {
  55643. // Update current
  55644. this._alive = this._particles.length > 0;
  55645. this.updateFunction(this._particles);
  55646. // Add new ones
  55647. var worldMatrix;
  55648. if (this.emitter.position) {
  55649. var emitterMesh = this.emitter;
  55650. worldMatrix = emitterMesh.getWorldMatrix();
  55651. }
  55652. else {
  55653. var emitterPosition = this.emitter;
  55654. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55655. }
  55656. var particle;
  55657. for (var index = 0; index < newParticles; index++) {
  55658. if (this._particles.length === this._capacity) {
  55659. break;
  55660. }
  55661. particle = this._createParticle();
  55662. this._particles.push(particle);
  55663. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55664. if (this.startPositionFunction) {
  55665. this.startPositionFunction(worldMatrix, particle.position, particle);
  55666. }
  55667. else {
  55668. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55669. }
  55670. if (this.startDirectionFunction) {
  55671. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55672. }
  55673. else {
  55674. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55675. }
  55676. if (emitPower === 0) {
  55677. if (!particle._initialDirection) {
  55678. particle._initialDirection = particle.direction.clone();
  55679. }
  55680. else {
  55681. particle._initialDirection.copyFrom(particle.direction);
  55682. }
  55683. }
  55684. else {
  55685. particle._initialDirection = null;
  55686. }
  55687. particle.direction.scaleInPlace(emitPower);
  55688. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55689. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55690. particle._initialSize = particle.size;
  55691. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55692. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55693. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55694. if (!this._colorGradients || this._colorGradients.length === 0) {
  55695. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55696. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55697. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55698. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55699. }
  55700. else {
  55701. this._colorGradients[0].getColorToRef(particle.color);
  55702. }
  55703. }
  55704. };
  55705. /** @hidden */
  55706. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55707. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55708. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55709. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55710. if (isAnimationSheetEnabled) {
  55711. attributeNamesOrOptions.push("cellIndex");
  55712. }
  55713. if (!isBillboardBased) {
  55714. attributeNamesOrOptions.push("direction");
  55715. }
  55716. return attributeNamesOrOptions;
  55717. };
  55718. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55719. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55720. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55721. if (isAnimationSheetEnabled) {
  55722. effectCreationOption.push("particlesInfos");
  55723. }
  55724. return effectCreationOption;
  55725. };
  55726. ParticleSystem.prototype._getEffect = function () {
  55727. if (this._customEffect) {
  55728. return this._customEffect;
  55729. }
  55730. ;
  55731. var defines = [];
  55732. if (this._scene.clipPlane) {
  55733. defines.push("#define CLIPPLANE");
  55734. }
  55735. if (this._isAnimationSheetEnabled) {
  55736. defines.push("#define ANIMATESHEET");
  55737. }
  55738. if (this._isBillboardBased) {
  55739. defines.push("#define BILLBOARD");
  55740. }
  55741. // Effect
  55742. var join = defines.join("\n");
  55743. if (this._cachedDefines !== join) {
  55744. this._cachedDefines = join;
  55745. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55746. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55747. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55748. }
  55749. return this._effect;
  55750. };
  55751. /**
  55752. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55753. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55754. */
  55755. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55756. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55757. if (!this._started)
  55758. return;
  55759. if (!preWarmOnly) {
  55760. var effect = this._getEffect();
  55761. // Check
  55762. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55763. return;
  55764. if (this._currentRenderId === this._scene.getRenderId()) {
  55765. return;
  55766. }
  55767. this._currentRenderId = this._scene.getRenderId();
  55768. }
  55769. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55770. // determine the number of particles we need to create
  55771. var newParticles;
  55772. if (this.manualEmitCount > -1) {
  55773. newParticles = this.manualEmitCount;
  55774. this._newPartsExcess = 0;
  55775. this.manualEmitCount = 0;
  55776. }
  55777. else {
  55778. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55779. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55780. }
  55781. if (this._newPartsExcess > 1.0) {
  55782. newParticles += this._newPartsExcess >> 0;
  55783. this._newPartsExcess -= this._newPartsExcess >> 0;
  55784. }
  55785. this._alive = false;
  55786. if (!this._stopped) {
  55787. this._actualFrame += this._scaledUpdateSpeed;
  55788. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55789. this.stop();
  55790. }
  55791. else {
  55792. newParticles = 0;
  55793. }
  55794. this._update(newParticles);
  55795. // Stopped?
  55796. if (this._stopped) {
  55797. if (!this._alive) {
  55798. this._started = false;
  55799. if (this.onAnimationEnd) {
  55800. this.onAnimationEnd();
  55801. }
  55802. if (this.disposeOnStop) {
  55803. this._scene._toBeDisposed.push(this);
  55804. }
  55805. }
  55806. }
  55807. if (!preWarmOnly) {
  55808. // Update VBO
  55809. var offset = 0;
  55810. for (var index = 0; index < this._particles.length; index++) {
  55811. var particle = this._particles[index];
  55812. this._appendParticleVertices(offset, particle);
  55813. offset += this._useInstancing ? 1 : 4;
  55814. }
  55815. if (this._vertexBuffer) {
  55816. this._vertexBuffer.update(this._vertexData);
  55817. }
  55818. }
  55819. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55820. this.stop();
  55821. }
  55822. };
  55823. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55824. this._appendParticleVertex(offset++, particle, 0, 0);
  55825. if (!this._useInstancing) {
  55826. this._appendParticleVertex(offset++, particle, 1, 0);
  55827. this._appendParticleVertex(offset++, particle, 1, 1);
  55828. this._appendParticleVertex(offset++, particle, 0, 1);
  55829. }
  55830. };
  55831. /**
  55832. * Rebuilds the particle system.
  55833. */
  55834. ParticleSystem.prototype.rebuild = function () {
  55835. this._createIndexBuffer();
  55836. if (this._vertexBuffer) {
  55837. this._vertexBuffer._rebuild();
  55838. }
  55839. };
  55840. /**
  55841. * Is this system ready to be used/rendered
  55842. * @return true if the system is ready
  55843. */
  55844. ParticleSystem.prototype.isReady = function () {
  55845. var effect = this._getEffect();
  55846. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55847. return false;
  55848. }
  55849. return true;
  55850. };
  55851. /**
  55852. * Renders the particle system in its current state.
  55853. * @returns the current number of particles
  55854. */
  55855. ParticleSystem.prototype.render = function () {
  55856. var effect = this._getEffect();
  55857. // Check
  55858. if (!this.isReady() || !this._particles.length) {
  55859. return 0;
  55860. }
  55861. var engine = this._scene.getEngine();
  55862. // Render
  55863. engine.enableEffect(effect);
  55864. engine.setState(false);
  55865. var viewMatrix = this._scene.getViewMatrix();
  55866. effect.setTexture("diffuseSampler", this.particleTexture);
  55867. effect.setMatrix("view", viewMatrix);
  55868. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55869. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55870. var baseSize = this.particleTexture.getBaseSize();
  55871. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55872. }
  55873. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55874. if (this._scene.clipPlane) {
  55875. var clipPlane = this._scene.clipPlane;
  55876. var invView = viewMatrix.clone();
  55877. invView.invert();
  55878. effect.setMatrix("invView", invView);
  55879. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55880. }
  55881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55882. // Draw order
  55883. switch (this.blendMode) {
  55884. case ParticleSystem.BLENDMODE_ADD:
  55885. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55886. break;
  55887. case ParticleSystem.BLENDMODE_ONEONE:
  55888. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55889. break;
  55890. case ParticleSystem.BLENDMODE_STANDARD:
  55891. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55892. break;
  55893. }
  55894. if (this.forceDepthWrite) {
  55895. engine.setDepthWrite(true);
  55896. }
  55897. if (this._useInstancing) {
  55898. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55899. engine.unbindInstanceAttributes();
  55900. }
  55901. else {
  55902. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55903. }
  55904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55905. return this._particles.length;
  55906. };
  55907. /**
  55908. * Disposes the particle system and free the associated resources
  55909. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55910. */
  55911. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55912. if (disposeTexture === void 0) { disposeTexture = true; }
  55913. if (this._vertexBuffer) {
  55914. this._vertexBuffer.dispose();
  55915. this._vertexBuffer = null;
  55916. }
  55917. if (this._spriteBuffer) {
  55918. this._spriteBuffer.dispose();
  55919. this._spriteBuffer = null;
  55920. }
  55921. if (this._indexBuffer) {
  55922. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55923. this._indexBuffer = null;
  55924. }
  55925. if (disposeTexture && this.particleTexture) {
  55926. this.particleTexture.dispose();
  55927. this.particleTexture = null;
  55928. }
  55929. this._removeFromRoot();
  55930. // Remove from scene
  55931. var index = this._scene.particleSystems.indexOf(this);
  55932. if (index > -1) {
  55933. this._scene.particleSystems.splice(index, 1);
  55934. }
  55935. // Callback
  55936. this.onDisposeObservable.notifyObservers(this);
  55937. this.onDisposeObservable.clear();
  55938. };
  55939. /**
  55940. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55941. * @param radius The radius of the sphere to emit from
  55942. * @returns the emitter
  55943. */
  55944. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55945. if (radius === void 0) { radius = 1; }
  55946. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55947. this.particleEmitterType = particleEmitter;
  55948. return particleEmitter;
  55949. };
  55950. /**
  55951. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55952. * @param radius The radius of the sphere to emit from
  55953. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55954. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55955. * @returns the emitter
  55956. */
  55957. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55958. if (radius === void 0) { radius = 1; }
  55959. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55960. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55961. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55962. this.particleEmitterType = particleEmitter;
  55963. return particleEmitter;
  55964. };
  55965. /**
  55966. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55967. * @param radius The radius of the cone to emit from
  55968. * @param angle The base angle of the cone
  55969. * @returns the emitter
  55970. */
  55971. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55972. if (radius === void 0) { radius = 1; }
  55973. if (angle === void 0) { angle = Math.PI / 4; }
  55974. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55975. this.particleEmitterType = particleEmitter;
  55976. return particleEmitter;
  55977. };
  55978. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  55979. /**
  55980. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55981. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55982. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55983. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55984. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55985. * @returns the emitter
  55986. */
  55987. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55988. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55989. this.particleEmitterType = particleEmitter;
  55990. this.direction1 = direction1;
  55991. this.direction2 = direction2;
  55992. this.minEmitBox = minEmitBox;
  55993. this.maxEmitBox = maxEmitBox;
  55994. return particleEmitter;
  55995. };
  55996. // Clone
  55997. /**
  55998. * Clones the particle system.
  55999. * @param name The name of the cloned object
  56000. * @param newEmitter The new emitter to use
  56001. * @returns the cloned particle system
  56002. */
  56003. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56004. var custom = null;
  56005. var program = null;
  56006. if (this.customShader != null) {
  56007. program = this.customShader;
  56008. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56009. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56010. }
  56011. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56012. result.customShader = program;
  56013. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56014. if (newEmitter === undefined) {
  56015. newEmitter = this.emitter;
  56016. }
  56017. result.emitter = newEmitter;
  56018. if (this.particleTexture) {
  56019. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56020. }
  56021. if (!this.preventAutoStart) {
  56022. result.start();
  56023. }
  56024. return result;
  56025. };
  56026. /**
  56027. * Serializes the particle system to a JSON object.
  56028. * @returns the JSON object
  56029. */
  56030. ParticleSystem.prototype.serialize = function () {
  56031. var serializationObject = {};
  56032. ParticleSystem._Serialize(serializationObject, this);
  56033. serializationObject.textureMask = this.textureMask.asArray();
  56034. serializationObject.customShader = this.customShader;
  56035. serializationObject.preventAutoStart = this.preventAutoStart;
  56036. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56037. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56038. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56039. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56040. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56041. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56042. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56043. return serializationObject;
  56044. };
  56045. /** @hidden */
  56046. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56047. serializationObject.name = particleSystem.name;
  56048. serializationObject.id = particleSystem.id;
  56049. serializationObject.capacity = particleSystem.getCapacity();
  56050. // Emitter
  56051. if (particleSystem.emitter.position) {
  56052. var emitterMesh = particleSystem.emitter;
  56053. serializationObject.emitterId = emitterMesh.id;
  56054. }
  56055. else {
  56056. var emitterPosition = particleSystem.emitter;
  56057. serializationObject.emitter = emitterPosition.asArray();
  56058. }
  56059. // Emitter
  56060. if (particleSystem.particleEmitterType) {
  56061. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56062. }
  56063. if (particleSystem.particleTexture) {
  56064. serializationObject.textureName = particleSystem.particleTexture.name;
  56065. }
  56066. // Animations
  56067. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56068. // Particle system
  56069. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56070. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56071. serializationObject.minSize = particleSystem.minSize;
  56072. serializationObject.maxSize = particleSystem.maxSize;
  56073. serializationObject.minScaleX = particleSystem.minScaleX;
  56074. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56075. serializationObject.minScaleY = particleSystem.minScaleY;
  56076. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56077. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56078. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56079. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56080. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56081. serializationObject.emitRate = particleSystem.emitRate;
  56082. serializationObject.gravity = particleSystem.gravity.asArray();
  56083. serializationObject.color1 = particleSystem.color1.asArray();
  56084. serializationObject.color2 = particleSystem.color2.asArray();
  56085. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56086. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56087. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56088. serializationObject.blendMode = particleSystem.blendMode;
  56089. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56090. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56091. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56092. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56093. var colorGradients = particleSystem.getColorGradients();
  56094. if (colorGradients) {
  56095. serializationObject.colorGradients = [];
  56096. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56097. var colorGradient = colorGradients_1[_i];
  56098. var serializedGradient = {
  56099. gradient: colorGradient.gradient,
  56100. color1: colorGradient.color1.asArray()
  56101. };
  56102. if (colorGradient.color2) {
  56103. serializedGradient.color2 = colorGradient.color2.asArray();
  56104. }
  56105. serializationObject.colorGradients.push(serializedGradient);
  56106. }
  56107. }
  56108. var sizeGradients = particleSystem.getSizeGradients();
  56109. if (sizeGradients) {
  56110. serializationObject.sizeGradients = [];
  56111. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56112. var sizeGradient = sizeGradients_1[_a];
  56113. serializationObject.sizeGradients.push({
  56114. gradient: sizeGradient.gradient,
  56115. factor: sizeGradient.factor
  56116. });
  56117. }
  56118. }
  56119. };
  56120. /** @hidden */
  56121. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56122. // Texture
  56123. if (parsedParticleSystem.textureName) {
  56124. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56125. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56126. }
  56127. // Emitter
  56128. if (parsedParticleSystem.emitterId) {
  56129. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56130. }
  56131. else {
  56132. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56133. }
  56134. // Animations
  56135. if (parsedParticleSystem.animations) {
  56136. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56137. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56138. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56139. }
  56140. }
  56141. if (parsedParticleSystem.autoAnimate) {
  56142. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56143. }
  56144. // Particle system
  56145. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56146. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56147. particleSystem.minSize = parsedParticleSystem.minSize;
  56148. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56149. if (parsedParticleSystem.minScaleX) {
  56150. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56151. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56152. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56153. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56154. }
  56155. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56156. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56157. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56158. }
  56159. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56160. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56161. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56162. }
  56163. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56164. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56165. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56166. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56167. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56168. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56169. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56170. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56171. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56172. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56173. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56174. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56175. if (parsedParticleSystem.colorGradients) {
  56176. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56177. var colorGradient = _a[_i];
  56178. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56179. }
  56180. }
  56181. if (parsedParticleSystem.sizeGradients) {
  56182. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56183. var sizeGradient = _c[_b];
  56184. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56185. }
  56186. }
  56187. // Emitter
  56188. if (parsedParticleSystem.particleEmitterType) {
  56189. var emitterType = void 0;
  56190. switch (parsedParticleSystem.particleEmitterType.type) {
  56191. case "SphereEmitter":
  56192. emitterType = new BABYLON.SphereParticleEmitter();
  56193. break;
  56194. case "SphereDirectedParticleEmitter":
  56195. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56196. break;
  56197. case "ConeEmitter":
  56198. emitterType = new BABYLON.ConeParticleEmitter();
  56199. break;
  56200. case "BoxEmitter":
  56201. default:
  56202. emitterType = new BABYLON.BoxParticleEmitter();
  56203. break;
  56204. }
  56205. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56206. particleSystem.particleEmitterType = emitterType;
  56207. }
  56208. };
  56209. /**
  56210. * Parses a JSON object to create a particle system.
  56211. * @param parsedParticleSystem The JSON object to parse
  56212. * @param scene The scene to create the particle system in
  56213. * @param rootUrl The root url to use to load external dependencies like texture
  56214. * @returns the Parsed particle system
  56215. */
  56216. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56217. var name = parsedParticleSystem.name;
  56218. var custom = null;
  56219. var program = null;
  56220. if (parsedParticleSystem.customShader) {
  56221. program = parsedParticleSystem.customShader;
  56222. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56223. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56224. }
  56225. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56226. particleSystem.customShader = program;
  56227. if (parsedParticleSystem.id) {
  56228. particleSystem.id = parsedParticleSystem.id;
  56229. }
  56230. // Auto start
  56231. if (parsedParticleSystem.preventAutoStart) {
  56232. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56233. }
  56234. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56235. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56236. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56237. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56238. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56239. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56240. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56241. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56242. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56243. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56244. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56245. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56246. if (!particleSystem.preventAutoStart) {
  56247. particleSystem.start();
  56248. }
  56249. return particleSystem;
  56250. };
  56251. /**
  56252. * Source color is added to the destination color without alpha affecting the result.
  56253. */
  56254. ParticleSystem.BLENDMODE_ONEONE = 0;
  56255. /**
  56256. * Blend current color and particle color using particle’s alpha.
  56257. */
  56258. ParticleSystem.BLENDMODE_STANDARD = 1;
  56259. /**
  56260. * Add current color and particle color multiplied by particle’s alpha.
  56261. */
  56262. ParticleSystem.BLENDMODE_ADD = 2;
  56263. return ParticleSystem;
  56264. }());
  56265. BABYLON.ParticleSystem = ParticleSystem;
  56266. })(BABYLON || (BABYLON = {}));
  56267. //# sourceMappingURL=babylon.particleSystem.js.map
  56268. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56269. var BABYLON;
  56270. (function (BABYLON) {
  56271. /**
  56272. * Particle emitter emitting particles from the inside of a box.
  56273. * It emits the particles randomly between 2 given directions.
  56274. */
  56275. var BoxParticleEmitter = /** @class */ (function () {
  56276. /**
  56277. * Creates a new instance BoxParticleEmitter
  56278. */
  56279. function BoxParticleEmitter() {
  56280. /**
  56281. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56282. */
  56283. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56284. /**
  56285. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56286. */
  56287. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56288. /**
  56289. * 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.
  56290. */
  56291. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56292. /**
  56293. * 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.
  56294. */
  56295. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56296. }
  56297. /**
  56298. * Called by the particle System when the direction is computed for the created particle.
  56299. * @param worldMatrix is the world matrix of the particle system
  56300. * @param directionToUpdate is the direction vector to update with the result
  56301. * @param particle is the particle we are computed the direction for
  56302. */
  56303. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56304. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56305. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56306. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56307. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56308. };
  56309. /**
  56310. * Called by the particle System when the position is computed for the created particle.
  56311. * @param worldMatrix is the world matrix of the particle system
  56312. * @param positionToUpdate is the position vector to update with the result
  56313. * @param particle is the particle we are computed the position for
  56314. */
  56315. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56316. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56317. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56318. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56319. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56320. };
  56321. /**
  56322. * Clones the current emitter and returns a copy of it
  56323. * @returns the new emitter
  56324. */
  56325. BoxParticleEmitter.prototype.clone = function () {
  56326. var newOne = new BoxParticleEmitter();
  56327. BABYLON.Tools.DeepCopy(this, newOne);
  56328. return newOne;
  56329. };
  56330. /**
  56331. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56332. * @param effect defines the update shader
  56333. */
  56334. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56335. effect.setVector3("direction1", this.direction1);
  56336. effect.setVector3("direction2", this.direction2);
  56337. effect.setVector3("minEmitBox", this.minEmitBox);
  56338. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56339. };
  56340. /**
  56341. * Returns a string to use to update the GPU particles update shader
  56342. * @returns a string containng the defines string
  56343. */
  56344. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56345. return "#define BOXEMITTER";
  56346. };
  56347. /**
  56348. * Returns the string "BoxEmitter"
  56349. * @returns a string containing the class name
  56350. */
  56351. BoxParticleEmitter.prototype.getClassName = function () {
  56352. return "BoxEmitter";
  56353. };
  56354. /**
  56355. * Serializes the particle system to a JSON object.
  56356. * @returns the JSON object
  56357. */
  56358. BoxParticleEmitter.prototype.serialize = function () {
  56359. var serializationObject = {};
  56360. serializationObject.type = this.getClassName();
  56361. serializationObject.direction1 = this.direction1.asArray();
  56362. serializationObject.direction2 = this.direction2.asArray();
  56363. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56364. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56365. return serializationObject;
  56366. };
  56367. /**
  56368. * Parse properties from a JSON object
  56369. * @param serializationObject defines the JSON object
  56370. */
  56371. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56372. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56373. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56374. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56375. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56376. };
  56377. return BoxParticleEmitter;
  56378. }());
  56379. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56380. })(BABYLON || (BABYLON = {}));
  56381. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56382. var BABYLON;
  56383. (function (BABYLON) {
  56384. /**
  56385. * Particle emitter emitting particles from the inside of a cone.
  56386. * It emits the particles alongside the cone volume from the base to the particle.
  56387. * The emission direction might be randomized.
  56388. */
  56389. var ConeParticleEmitter = /** @class */ (function () {
  56390. /**
  56391. * Creates a new instance ConeParticleEmitter
  56392. * @param radius the radius of the emission cone (1 by default)
  56393. * @param angles the cone base angle (PI by default)
  56394. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56395. */
  56396. function ConeParticleEmitter(radius, angle,
  56397. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56398. directionRandomizer) {
  56399. if (radius === void 0) { radius = 1; }
  56400. if (angle === void 0) { angle = Math.PI; }
  56401. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56402. this.directionRandomizer = directionRandomizer;
  56403. this.angle = angle;
  56404. this.radius = radius;
  56405. }
  56406. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56407. /**
  56408. * Gets or sets the radius of the emission cone
  56409. */
  56410. get: function () {
  56411. return this._radius;
  56412. },
  56413. set: function (value) {
  56414. this._radius = value;
  56415. this._buildHeight();
  56416. },
  56417. enumerable: true,
  56418. configurable: true
  56419. });
  56420. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56421. /**
  56422. * Gets or sets the angle of the emission cone
  56423. */
  56424. get: function () {
  56425. return this._angle;
  56426. },
  56427. set: function (value) {
  56428. this._angle = value;
  56429. this._buildHeight();
  56430. },
  56431. enumerable: true,
  56432. configurable: true
  56433. });
  56434. ConeParticleEmitter.prototype._buildHeight = function () {
  56435. if (this._angle !== 0) {
  56436. this._height = this._radius / Math.tan(this._angle / 2);
  56437. }
  56438. else {
  56439. this._height = 1;
  56440. }
  56441. };
  56442. /**
  56443. * Called by the particle System when the direction is computed for the created particle.
  56444. * @param worldMatrix is the world matrix of the particle system
  56445. * @param directionToUpdate is the direction vector to update with the result
  56446. * @param particle is the particle we are computed the direction for
  56447. */
  56448. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56449. if (this._angle === 0) {
  56450. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56451. }
  56452. else {
  56453. // measure the direction Vector from the emitter to the particle.
  56454. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56455. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56456. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56457. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56458. direction.x += randX;
  56459. direction.y += randY;
  56460. direction.z += randZ;
  56461. direction.normalize();
  56462. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56463. }
  56464. };
  56465. /**
  56466. * Called by the particle System when the position is computed for the created particle.
  56467. * @param worldMatrix is the world matrix of the particle system
  56468. * @param positionToUpdate is the position vector to update with the result
  56469. * @param particle is the particle we are computed the position for
  56470. */
  56471. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56472. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56473. var h = BABYLON.Scalar.RandomRange(0, 1);
  56474. // Better distribution in a cone at normal angles.
  56475. h = 1 - h * h;
  56476. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56477. radius = radius * h;
  56478. var randX = radius * Math.sin(s);
  56479. var randZ = radius * Math.cos(s);
  56480. var randY = h * this._height;
  56481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56482. };
  56483. /**
  56484. * Clones the current emitter and returns a copy of it
  56485. * @returns the new emitter
  56486. */
  56487. ConeParticleEmitter.prototype.clone = function () {
  56488. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56489. BABYLON.Tools.DeepCopy(this, newOne);
  56490. return newOne;
  56491. };
  56492. /**
  56493. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56494. * @param effect defines the update shader
  56495. */
  56496. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56497. effect.setFloat("radius", this._radius);
  56498. effect.setFloat("coneAngle", this._angle);
  56499. effect.setFloat("height", this._height);
  56500. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56501. };
  56502. /**
  56503. * Returns a string to use to update the GPU particles update shader
  56504. * @returns a string containng the defines string
  56505. */
  56506. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56507. return "#define CONEEMITTER";
  56508. };
  56509. /**
  56510. * Returns the string "BoxEmitter"
  56511. * @returns a string containing the class name
  56512. */
  56513. ConeParticleEmitter.prototype.getClassName = function () {
  56514. return "ConeEmitter";
  56515. };
  56516. /**
  56517. * Serializes the particle system to a JSON object.
  56518. * @returns the JSON object
  56519. */
  56520. ConeParticleEmitter.prototype.serialize = function () {
  56521. var serializationObject = {};
  56522. serializationObject.type = this.getClassName();
  56523. serializationObject.radius = this._radius;
  56524. serializationObject.angle = this._angle;
  56525. serializationObject.directionRandomizer = this.directionRandomizer;
  56526. return serializationObject;
  56527. };
  56528. /**
  56529. * Parse properties from a JSON object
  56530. * @param serializationObject defines the JSON object
  56531. */
  56532. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56533. this.radius = serializationObject.radius;
  56534. this.angle = serializationObject.angle;
  56535. this.directionRandomizer = serializationObject.directionRandomizer;
  56536. };
  56537. return ConeParticleEmitter;
  56538. }());
  56539. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56540. })(BABYLON || (BABYLON = {}));
  56541. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56542. var BABYLON;
  56543. (function (BABYLON) {
  56544. /**
  56545. * Particle emitter emitting particles from the inside of a sphere.
  56546. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56547. */
  56548. var SphereParticleEmitter = /** @class */ (function () {
  56549. /**
  56550. * Creates a new instance SphereParticleEmitter
  56551. * @param radius the radius of the emission sphere (1 by default)
  56552. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56553. */
  56554. function SphereParticleEmitter(
  56555. /**
  56556. * The radius of the emission sphere.
  56557. */
  56558. radius,
  56559. /**
  56560. * How much to randomize the particle direction [0-1].
  56561. */
  56562. directionRandomizer) {
  56563. if (radius === void 0) { radius = 1; }
  56564. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56565. this.radius = radius;
  56566. this.directionRandomizer = directionRandomizer;
  56567. /**
  56568. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56569. */
  56570. this.radiusRange = 1;
  56571. }
  56572. /**
  56573. * Called by the particle System when the direction is computed for the created particle.
  56574. * @param worldMatrix is the world matrix of the particle system
  56575. * @param directionToUpdate is the direction vector to update with the result
  56576. * @param particle is the particle we are computed the direction for
  56577. */
  56578. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56579. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56580. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56581. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56582. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56583. direction.x += randX;
  56584. direction.y += randY;
  56585. direction.z += randZ;
  56586. direction.normalize();
  56587. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56588. };
  56589. /**
  56590. * Called by the particle System when the position is computed for the created particle.
  56591. * @param worldMatrix is the world matrix of the particle system
  56592. * @param positionToUpdate is the position vector to update with the result
  56593. * @param particle is the particle we are computed the position for
  56594. */
  56595. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56596. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56597. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56598. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56599. var theta = Math.acos(2 * v - 1);
  56600. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56601. var randY = randRadius * Math.cos(theta);
  56602. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56604. };
  56605. /**
  56606. * Clones the current emitter and returns a copy of it
  56607. * @returns the new emitter
  56608. */
  56609. SphereParticleEmitter.prototype.clone = function () {
  56610. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56611. BABYLON.Tools.DeepCopy(this, newOne);
  56612. return newOne;
  56613. };
  56614. /**
  56615. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56616. * @param effect defines the update shader
  56617. */
  56618. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56619. effect.setFloat("radius", this.radius);
  56620. effect.setFloat("radiusRange", this.radiusRange);
  56621. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56622. };
  56623. /**
  56624. * Returns a string to use to update the GPU particles update shader
  56625. * @returns a string containng the defines string
  56626. */
  56627. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56628. return "#define SPHEREEMITTER";
  56629. };
  56630. /**
  56631. * Returns the string "SphereParticleEmitter"
  56632. * @returns a string containing the class name
  56633. */
  56634. SphereParticleEmitter.prototype.getClassName = function () {
  56635. return "SphereParticleEmitter";
  56636. };
  56637. /**
  56638. * Serializes the particle system to a JSON object.
  56639. * @returns the JSON object
  56640. */
  56641. SphereParticleEmitter.prototype.serialize = function () {
  56642. var serializationObject = {};
  56643. serializationObject.type = this.getClassName();
  56644. serializationObject.radius = this.radius;
  56645. serializationObject.directionRandomizer = this.directionRandomizer;
  56646. return serializationObject;
  56647. };
  56648. /**
  56649. * Parse properties from a JSON object
  56650. * @param serializationObject defines the JSON object
  56651. */
  56652. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56653. this.radius = serializationObject.radius;
  56654. this.directionRandomizer = serializationObject.directionRandomizer;
  56655. };
  56656. return SphereParticleEmitter;
  56657. }());
  56658. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56659. /**
  56660. * Particle emitter emitting particles from the inside of a sphere.
  56661. * It emits the particles randomly between two vectors.
  56662. */
  56663. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56664. __extends(SphereDirectedParticleEmitter, _super);
  56665. /**
  56666. * Creates a new instance SphereDirectedParticleEmitter
  56667. * @param radius the radius of the emission sphere (1 by default)
  56668. * @param direction1 the min limit of the emission direction (up vector by default)
  56669. * @param direction2 the max limit of the emission direction (up vector by default)
  56670. */
  56671. function SphereDirectedParticleEmitter(radius,
  56672. /**
  56673. * The min limit of the emission direction.
  56674. */
  56675. direction1,
  56676. /**
  56677. * The max limit of the emission direction.
  56678. */
  56679. direction2) {
  56680. if (radius === void 0) { radius = 1; }
  56681. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56682. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56683. var _this = _super.call(this, radius) || this;
  56684. _this.direction1 = direction1;
  56685. _this.direction2 = direction2;
  56686. return _this;
  56687. }
  56688. /**
  56689. * Called by the particle System when the direction is computed for the created particle.
  56690. * @param worldMatrix is the world matrix of the particle system
  56691. * @param directionToUpdate is the direction vector to update with the result
  56692. * @param particle is the particle we are computed the direction for
  56693. */
  56694. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56695. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56696. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56697. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56698. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56699. };
  56700. /**
  56701. * Clones the current emitter and returns a copy of it
  56702. * @returns the new emitter
  56703. */
  56704. SphereDirectedParticleEmitter.prototype.clone = function () {
  56705. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56706. BABYLON.Tools.DeepCopy(this, newOne);
  56707. return newOne;
  56708. };
  56709. /**
  56710. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56711. * @param effect defines the update shader
  56712. */
  56713. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56714. effect.setFloat("radius", this.radius);
  56715. effect.setFloat("radiusRange", this.radiusRange);
  56716. effect.setVector3("direction1", this.direction1);
  56717. effect.setVector3("direction2", this.direction2);
  56718. };
  56719. /**
  56720. * Returns a string to use to update the GPU particles update shader
  56721. * @returns a string containng the defines string
  56722. */
  56723. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56724. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56725. };
  56726. /**
  56727. * Returns the string "SphereDirectedParticleEmitter"
  56728. * @returns a string containing the class name
  56729. */
  56730. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56731. return "SphereDirectedParticleEmitter";
  56732. };
  56733. /**
  56734. * Serializes the particle system to a JSON object.
  56735. * @returns the JSON object
  56736. */
  56737. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56738. var serializationObject = _super.prototype.serialize.call(this);
  56739. serializationObject.direction1 = this.direction1.asArray();
  56740. serializationObject.direction2 = this.direction2.asArray();
  56741. return serializationObject;
  56742. };
  56743. /**
  56744. * Parse properties from a JSON object
  56745. * @param serializationObject defines the JSON object
  56746. */
  56747. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56748. _super.prototype.parse.call(this, serializationObject);
  56749. this.direction1.copyFrom(serializationObject.direction1);
  56750. this.direction2.copyFrom(serializationObject.direction2);
  56751. };
  56752. return SphereDirectedParticleEmitter;
  56753. }(SphereParticleEmitter));
  56754. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56755. })(BABYLON || (BABYLON = {}));
  56756. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56757. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56758. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56759. s = arguments[i];
  56760. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56761. t[p] = s[p];
  56762. }
  56763. return t;
  56764. };
  56765. var BABYLON;
  56766. (function (BABYLON) {
  56767. /**
  56768. * This represents a GPU particle system in Babylon
  56769. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56770. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56771. */
  56772. var GPUParticleSystem = /** @class */ (function () {
  56773. /**
  56774. * Instantiates a GPU particle system.
  56775. * 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.
  56776. * @param name The name of the particle system
  56777. * @param capacity The max number of particles alive at the same time
  56778. * @param scene The scene the particle system belongs to
  56779. */
  56780. function GPUParticleSystem(name, options, scene) {
  56781. /**
  56782. * The emitter represents the Mesh or position we are attaching the particle system to.
  56783. */
  56784. this.emitter = null;
  56785. /**
  56786. * The rendering group used by the Particle system to chose when to render.
  56787. */
  56788. this.renderingGroupId = 0;
  56789. /**
  56790. * The layer mask we are rendering the particles through.
  56791. */
  56792. this.layerMask = 0x0FFFFFFF;
  56793. this._accumulatedCount = 0;
  56794. this._targetIndex = 0;
  56795. this._currentRenderId = -1;
  56796. this._started = false;
  56797. this._stopped = false;
  56798. this._timeDelta = 0;
  56799. this._attributesStrideSize = 21;
  56800. this._actualFrame = 0;
  56801. /**
  56802. * List of animations used by the particle system.
  56803. */
  56804. this.animations = [];
  56805. /**
  56806. * An event triggered when the system is disposed.
  56807. */
  56808. this.onDisposeObservable = new BABYLON.Observable();
  56809. /**
  56810. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56811. */
  56812. this.updateSpeed = 0.01;
  56813. /**
  56814. * The amount of time the particle system is running (depends of the overall update speed).
  56815. */
  56816. this.targetStopDuration = 0;
  56817. /**
  56818. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56819. */
  56820. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56821. /**
  56822. * Minimum life time of emitting particles.
  56823. */
  56824. this.minLifeTime = 1;
  56825. /**
  56826. * Maximum life time of emitting particles.
  56827. */
  56828. this.maxLifeTime = 1;
  56829. /**
  56830. * Minimum Size of emitting particles.
  56831. */
  56832. this.minSize = 1;
  56833. /**
  56834. * Maximum Size of emitting particles.
  56835. */
  56836. this.maxSize = 1;
  56837. /**
  56838. * Minimum scale of emitting particles on X axis.
  56839. */
  56840. this.minScaleX = 1;
  56841. /**
  56842. * Maximum scale of emitting particles on X axis.
  56843. */
  56844. this.maxScaleX = 1;
  56845. /**
  56846. * Minimum scale of emitting particles on Y axis.
  56847. */
  56848. this.minScaleY = 1;
  56849. /**
  56850. * Maximum scale of emitting particles on Y axis.
  56851. */
  56852. this.maxScaleY = 1;
  56853. /**
  56854. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56855. */
  56856. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56857. /**
  56858. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56859. */
  56860. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56861. /**
  56862. * Color the particle will have at the end of its lifetime.
  56863. */
  56864. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56865. /**
  56866. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56867. */
  56868. this.emitRate = 100;
  56869. /**
  56870. * You can use gravity if you want to give an orientation to your particles.
  56871. */
  56872. this.gravity = BABYLON.Vector3.Zero();
  56873. /**
  56874. * Minimum power of emitting particles.
  56875. */
  56876. this.minEmitPower = 1;
  56877. /**
  56878. * Maximum power of emitting particles.
  56879. */
  56880. this.maxEmitPower = 1;
  56881. /**
  56882. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56883. */
  56884. this.minAngularSpeed = 0;
  56885. /**
  56886. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56887. */
  56888. this.maxAngularSpeed = 0;
  56889. /**
  56890. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56891. * to override the particles.
  56892. */
  56893. this.forceDepthWrite = false;
  56894. this._preWarmDone = false;
  56895. /** 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 */
  56896. this.preWarmCycles = 0;
  56897. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56898. this.preWarmStepOffset = 1;
  56899. /**
  56900. * Gets or sets the minimal initial rotation in radians.
  56901. */
  56902. this.minInitialRotation = 0;
  56903. /**
  56904. * Gets or sets the maximal initial rotation in radians.
  56905. */
  56906. this.maxInitialRotation = 0;
  56907. this._isBillboardBased = true;
  56908. this._colorGradients = null;
  56909. this._sizeGradients = null;
  56910. this.id = name;
  56911. this.name = name;
  56912. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56913. this._engine = this._scene.getEngine();
  56914. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56915. var optionsAsNumber = options;
  56916. if (isFinite(optionsAsNumber)) {
  56917. fullOptions.capacity = optionsAsNumber;
  56918. }
  56919. this._capacity = fullOptions.capacity;
  56920. this._activeCount = fullOptions.capacity;
  56921. this._currentActiveCount = 0;
  56922. this._scene.particleSystems.push(this);
  56923. this._updateEffectOptions = {
  56924. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  56925. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56926. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56927. "angleRange", "radiusRange"],
  56928. uniformBuffersNames: [],
  56929. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  56930. defines: "",
  56931. fallbacks: null,
  56932. onCompiled: null,
  56933. onError: null,
  56934. indexParameters: null,
  56935. maxSimultaneousLights: 0,
  56936. transformFeedbackVaryings: []
  56937. };
  56938. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56939. // Random data
  56940. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56941. var d = [];
  56942. for (var i = 0; i < maxTextureSize; ++i) {
  56943. d.push(Math.random());
  56944. d.push(Math.random());
  56945. d.push(Math.random());
  56946. d.push(Math.random());
  56947. }
  56948. 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);
  56949. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56950. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56951. d = [];
  56952. for (var i = 0; i < maxTextureSize; ++i) {
  56953. d.push(Math.random());
  56954. d.push(Math.random());
  56955. d.push(Math.random());
  56956. d.push(Math.random());
  56957. }
  56958. 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);
  56959. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56960. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56961. this._randomTextureSize = maxTextureSize;
  56962. }
  56963. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56964. /**
  56965. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56966. */
  56967. get: function () {
  56968. if (!BABYLON.Engine.LastCreatedEngine) {
  56969. return false;
  56970. }
  56971. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56972. },
  56973. enumerable: true,
  56974. configurable: true
  56975. });
  56976. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56977. /**
  56978. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56979. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56980. */
  56981. get: function () {
  56982. if (this.particleEmitterType.direction1) {
  56983. return this.particleEmitterType.direction1;
  56984. }
  56985. return BABYLON.Vector3.Zero();
  56986. },
  56987. set: function (value) {
  56988. if (this.particleEmitterType.direction1) {
  56989. this.particleEmitterType.direction1 = value;
  56990. }
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56996. /**
  56997. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56998. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56999. */
  57000. get: function () {
  57001. if (this.particleEmitterType.direction2) {
  57002. return this.particleEmitterType.direction2;
  57003. }
  57004. return BABYLON.Vector3.Zero();
  57005. },
  57006. set: function (value) {
  57007. if (this.particleEmitterType.direction2) {
  57008. this.particleEmitterType.direction2 = value;
  57009. }
  57010. },
  57011. enumerable: true,
  57012. configurable: true
  57013. });
  57014. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57015. /**
  57016. * 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.
  57017. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57018. */
  57019. get: function () {
  57020. if (this.particleEmitterType.minEmitBox) {
  57021. return this.particleEmitterType.minEmitBox;
  57022. }
  57023. return BABYLON.Vector3.Zero();
  57024. },
  57025. set: function (value) {
  57026. if (this.particleEmitterType.minEmitBox) {
  57027. this.particleEmitterType.minEmitBox = value;
  57028. }
  57029. },
  57030. enumerable: true,
  57031. configurable: true
  57032. });
  57033. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57034. /**
  57035. * 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.
  57036. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57037. */
  57038. get: function () {
  57039. if (this.particleEmitterType.maxEmitBox) {
  57040. return this.particleEmitterType.maxEmitBox;
  57041. }
  57042. return BABYLON.Vector3.Zero();
  57043. },
  57044. set: function (value) {
  57045. if (this.particleEmitterType.maxEmitBox) {
  57046. this.particleEmitterType.maxEmitBox = value;
  57047. }
  57048. },
  57049. enumerable: true,
  57050. configurable: true
  57051. });
  57052. /**
  57053. * Gets the maximum number of particles active at the same time.
  57054. * @returns The max number of active particles.
  57055. */
  57056. GPUParticleSystem.prototype.getCapacity = function () {
  57057. return this._capacity;
  57058. };
  57059. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57060. /**
  57061. * Gets or set the number of active particles
  57062. */
  57063. get: function () {
  57064. return this._activeCount;
  57065. },
  57066. set: function (value) {
  57067. this._activeCount = Math.min(value, this._capacity);
  57068. },
  57069. enumerable: true,
  57070. configurable: true
  57071. });
  57072. /**
  57073. * Is this system ready to be used/rendered
  57074. * @return true if the system is ready
  57075. */
  57076. GPUParticleSystem.prototype.isReady = function () {
  57077. if (!this._updateEffect) {
  57078. this._recreateUpdateEffect();
  57079. this._recreateRenderEffect();
  57080. return false;
  57081. }
  57082. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57083. return false;
  57084. }
  57085. return true;
  57086. };
  57087. /**
  57088. * Gets Wether the system has been started.
  57089. * @returns True if it has been started, otherwise false.
  57090. */
  57091. GPUParticleSystem.prototype.isStarted = function () {
  57092. return this._started;
  57093. };
  57094. /**
  57095. * Starts the particle system and begins to emit.
  57096. */
  57097. GPUParticleSystem.prototype.start = function () {
  57098. this._started = true;
  57099. this._stopped = false;
  57100. this._preWarmDone = false;
  57101. };
  57102. /**
  57103. * Stops the particle system.
  57104. */
  57105. GPUParticleSystem.prototype.stop = function () {
  57106. this._stopped = true;
  57107. };
  57108. /**
  57109. * Remove all active particles
  57110. */
  57111. GPUParticleSystem.prototype.reset = function () {
  57112. this._releaseBuffers();
  57113. this._releaseVAOs();
  57114. this._currentActiveCount = 0;
  57115. this._targetIndex = 0;
  57116. };
  57117. /**
  57118. * Returns the string "GPUParticleSystem"
  57119. * @returns a string containing the class name
  57120. */
  57121. GPUParticleSystem.prototype.getClassName = function () {
  57122. return "GPUParticleSystem";
  57123. };
  57124. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57125. /**
  57126. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57127. */
  57128. get: function () {
  57129. return this._isBillboardBased;
  57130. },
  57131. set: function (value) {
  57132. if (this._isBillboardBased === value) {
  57133. return;
  57134. }
  57135. this._isBillboardBased = value;
  57136. this._releaseBuffers();
  57137. },
  57138. enumerable: true,
  57139. configurable: true
  57140. });
  57141. /**
  57142. * Gets the current list of color gradients.
  57143. * You must use addColorGradient and removeColorGradient to udpate this list
  57144. * @returns the list of color gradients
  57145. */
  57146. GPUParticleSystem.prototype.getColorGradients = function () {
  57147. return this._colorGradients;
  57148. };
  57149. /**
  57150. * Gets the current list of size gradients.
  57151. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57152. * @returns the list of size gradients
  57153. */
  57154. GPUParticleSystem.prototype.getSizeGradients = function () {
  57155. return this._sizeGradients;
  57156. };
  57157. /**
  57158. * Adds a new color gradient
  57159. * @param gradient defines the gradient to use (between 0 and 1)
  57160. * @param color defines the color to affect to the specified gradient
  57161. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57162. */
  57163. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57164. if (!this._colorGradients) {
  57165. this._colorGradients = [];
  57166. }
  57167. var colorGradient = new BABYLON.ColorGradient();
  57168. colorGradient.gradient = gradient;
  57169. colorGradient.color1 = color1;
  57170. this._colorGradients.push(colorGradient);
  57171. this._colorGradients.sort(function (a, b) {
  57172. if (a.gradient < b.gradient) {
  57173. return -1;
  57174. }
  57175. else if (a.gradient > b.gradient) {
  57176. return 1;
  57177. }
  57178. return 0;
  57179. });
  57180. if (this._colorGradientsTexture) {
  57181. this._colorGradientsTexture.dispose();
  57182. this._colorGradientsTexture = null;
  57183. }
  57184. this._releaseBuffers();
  57185. return this;
  57186. };
  57187. /**
  57188. * Remove a specific color gradient
  57189. * @param gradient defines the gradient to remove
  57190. */
  57191. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57192. if (!this._colorGradients) {
  57193. return this;
  57194. }
  57195. var index = 0;
  57196. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57197. var colorGradient = _a[_i];
  57198. if (colorGradient.gradient === gradient) {
  57199. this._colorGradients.splice(index, 1);
  57200. break;
  57201. }
  57202. index++;
  57203. }
  57204. if (this._colorGradientsTexture) {
  57205. this._colorGradientsTexture.dispose();
  57206. this._colorGradientsTexture = null;
  57207. }
  57208. this._releaseBuffers();
  57209. return this;
  57210. };
  57211. /**
  57212. * Adds a new size gradient
  57213. * @param gradient defines the gradient to use (between 0 and 1)
  57214. * @param factor defines the size factor to affect to the specified gradient
  57215. */
  57216. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57217. if (!this._sizeGradients) {
  57218. this._sizeGradients = [];
  57219. }
  57220. var sizeGradient = new BABYLON.FactorGradient();
  57221. sizeGradient.gradient = gradient;
  57222. sizeGradient.factor = factor;
  57223. this._sizeGradients.push(sizeGradient);
  57224. this._sizeGradients.sort(function (a, b) {
  57225. if (a.gradient < b.gradient) {
  57226. return -1;
  57227. }
  57228. else if (a.gradient > b.gradient) {
  57229. return 1;
  57230. }
  57231. return 0;
  57232. });
  57233. if (this._sizeGradientsTexture) {
  57234. this._sizeGradientsTexture.dispose();
  57235. this._sizeGradientsTexture = null;
  57236. }
  57237. this._releaseBuffers();
  57238. return this;
  57239. };
  57240. /**
  57241. * Remove a specific size gradient
  57242. * @param gradient defines the gradient to remove
  57243. */
  57244. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57245. if (!this._sizeGradients) {
  57246. return this;
  57247. }
  57248. var index = 0;
  57249. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57250. var sizeGradient = _a[_i];
  57251. if (sizeGradient.gradient === gradient) {
  57252. this._sizeGradients.splice(index, 1);
  57253. break;
  57254. }
  57255. index++;
  57256. }
  57257. if (this._sizeGradientsTexture) {
  57258. this._sizeGradientsTexture.dispose();
  57259. this._sizeGradientsTexture = null;
  57260. }
  57261. this._releaseBuffers();
  57262. return this;
  57263. };
  57264. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57265. var updateVertexBuffers = {};
  57266. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57267. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57268. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57269. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57270. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57271. var offset = 12;
  57272. if (this._sizeGradientsTexture) {
  57273. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57274. offset += 3;
  57275. }
  57276. if (!this._colorGradientsTexture) {
  57277. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57278. offset += 4;
  57279. }
  57280. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57281. offset += 3;
  57282. if (!this._isBillboardBased) {
  57283. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57284. offset += 3;
  57285. }
  57286. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57287. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57288. this._engine.bindArrayBuffer(null);
  57289. return vao;
  57290. };
  57291. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57292. var renderVertexBuffers = {};
  57293. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57294. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57295. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57296. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57297. var offset = 12;
  57298. if (this._sizeGradientsTexture) {
  57299. offset += 3;
  57300. }
  57301. if (!this._colorGradientsTexture) {
  57302. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57303. offset += 4;
  57304. }
  57305. offset += 3; // Direction
  57306. if (!this._isBillboardBased) {
  57307. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57308. offset += 3;
  57309. }
  57310. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57311. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57312. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57313. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57314. this._engine.bindArrayBuffer(null);
  57315. return vao;
  57316. };
  57317. GPUParticleSystem.prototype._initialize = function (force) {
  57318. if (force === void 0) { force = false; }
  57319. if (this._buffer0 && !force) {
  57320. return;
  57321. }
  57322. var engine = this._scene.getEngine();
  57323. var data = new Array();
  57324. if (!this.isBillboardBased) {
  57325. this._attributesStrideSize += 3;
  57326. }
  57327. if (this._colorGradientsTexture) {
  57328. this._attributesStrideSize -= 4;
  57329. }
  57330. if (this._sizeGradientsTexture) {
  57331. this._attributesStrideSize += 3;
  57332. }
  57333. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57334. // position
  57335. data.push(0.0);
  57336. data.push(0.0);
  57337. data.push(0.0);
  57338. // Age and life
  57339. data.push(0.0); // create the particle as a dead one to create a new one at start
  57340. data.push(0.0);
  57341. // Seed
  57342. data.push(Math.random());
  57343. data.push(Math.random());
  57344. data.push(Math.random());
  57345. data.push(Math.random());
  57346. // Size
  57347. data.push(0.0);
  57348. data.push(0.0);
  57349. data.push(0.0);
  57350. if (this._sizeGradientsTexture) {
  57351. data.push(0.0);
  57352. data.push(0.0);
  57353. data.push(0.0);
  57354. }
  57355. if (!this._colorGradientsTexture) {
  57356. // color
  57357. data.push(0.0);
  57358. data.push(0.0);
  57359. data.push(0.0);
  57360. data.push(0.0);
  57361. }
  57362. // direction
  57363. data.push(0.0);
  57364. data.push(0.0);
  57365. data.push(0.0);
  57366. if (!this.isBillboardBased) {
  57367. // initialDirection
  57368. data.push(0.0);
  57369. data.push(0.0);
  57370. data.push(0.0);
  57371. }
  57372. // angle
  57373. data.push(0.0);
  57374. data.push(0.0);
  57375. }
  57376. // Sprite data
  57377. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57378. -0.5, 0.5, 0, 1,
  57379. -0.5, -0.5, 0, 0,
  57380. 0.5, -0.5, 1, 0]);
  57381. // Buffers
  57382. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57383. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57384. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57385. // Update VAO
  57386. this._updateVAO = [];
  57387. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57388. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57389. // Render VAO
  57390. this._renderVAO = [];
  57391. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57392. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57393. // Links
  57394. this._sourceBuffer = this._buffer0;
  57395. this._targetBuffer = this._buffer1;
  57396. };
  57397. /** @hidden */
  57398. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57399. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57400. if (this._isBillboardBased) {
  57401. defines += "\n#define BILLBOARD";
  57402. }
  57403. if (this._colorGradientsTexture) {
  57404. defines += "\n#define COLORGRADIENTS";
  57405. }
  57406. if (this._sizeGradientsTexture) {
  57407. defines += "\n#define SIZEGRADIENTS";
  57408. }
  57409. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57410. return;
  57411. }
  57412. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57413. if (this._sizeGradientsTexture) {
  57414. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57415. }
  57416. if (!this._colorGradientsTexture) {
  57417. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57418. }
  57419. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57420. if (!this._isBillboardBased) {
  57421. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57422. }
  57423. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57424. this._updateEffectOptions.defines = defines;
  57425. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57426. };
  57427. /** @hidden */
  57428. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57429. var defines = "";
  57430. if (this._scene.clipPlane) {
  57431. defines = "\n#define CLIPPLANE";
  57432. }
  57433. if (this._isBillboardBased) {
  57434. defines += "\n#define BILLBOARD";
  57435. }
  57436. if (this._colorGradientsTexture) {
  57437. defines += "\n#define COLORGRADIENTS";
  57438. }
  57439. if (this._renderEffect && this._renderEffect.defines === defines) {
  57440. return;
  57441. }
  57442. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57443. };
  57444. /**
  57445. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57446. * @param preWarm defines if we are in the pre-warmimg phase
  57447. */
  57448. GPUParticleSystem.prototype.animate = function (preWarm) {
  57449. if (preWarm === void 0) { preWarm = false; }
  57450. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57451. this._actualFrame += this._timeDelta;
  57452. if (!this._stopped) {
  57453. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57454. this.stop();
  57455. }
  57456. }
  57457. };
  57458. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57459. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57460. return;
  57461. }
  57462. var textureWidth = 256;
  57463. var data = new Float32Array(textureWidth);
  57464. for (var x = 0; x < textureWidth; x++) {
  57465. var ratio = x / textureWidth;
  57466. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57467. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57468. });
  57469. }
  57470. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57471. };
  57472. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57473. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57474. return;
  57475. }
  57476. var textureWidth = 256;
  57477. var data = new Uint8Array(textureWidth * 4);
  57478. var tmpColor = BABYLON.Tmp.Color4[0];
  57479. for (var x = 0; x < textureWidth; x++) {
  57480. var ratio = x / textureWidth;
  57481. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57482. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57483. data[x * 4] = tmpColor.r * 255;
  57484. data[x * 4 + 1] = tmpColor.g * 255;
  57485. data[x * 4 + 2] = tmpColor.b * 255;
  57486. data[x * 4 + 3] = tmpColor.a * 255;
  57487. });
  57488. }
  57489. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57490. };
  57491. /**
  57492. * Renders the particle system in its current state
  57493. * @param preWarm defines if the system should only update the particles but not render them
  57494. * @returns the current number of particles
  57495. */
  57496. GPUParticleSystem.prototype.render = function (preWarm) {
  57497. if (preWarm === void 0) { preWarm = false; }
  57498. if (!this._started) {
  57499. return 0;
  57500. }
  57501. this._createColorGradientTexture();
  57502. this._createSizeGradientTexture();
  57503. this._recreateUpdateEffect();
  57504. this._recreateRenderEffect();
  57505. if (!this.isReady()) {
  57506. return 0;
  57507. }
  57508. if (!preWarm) {
  57509. if (!this._preWarmDone && this.preWarmCycles) {
  57510. for (var index = 0; index < this.preWarmCycles; index++) {
  57511. this.animate(true);
  57512. this.render(true);
  57513. }
  57514. this._preWarmDone = true;
  57515. }
  57516. if (this._currentRenderId === this._scene.getRenderId()) {
  57517. return 0;
  57518. }
  57519. this._currentRenderId = this._scene.getRenderId();
  57520. }
  57521. // Get everything ready to render
  57522. this._initialize();
  57523. this._accumulatedCount += this.emitRate * this._timeDelta;
  57524. if (this._accumulatedCount > 1) {
  57525. var intPart = this._accumulatedCount | 0;
  57526. this._accumulatedCount -= intPart;
  57527. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57528. }
  57529. if (!this._currentActiveCount) {
  57530. return 0;
  57531. }
  57532. // Enable update effect
  57533. this._engine.enableEffect(this._updateEffect);
  57534. this._engine.setState(false);
  57535. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57536. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57537. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57538. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57539. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57540. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57541. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57542. if (!this._colorGradientsTexture) {
  57543. this._updateEffect.setDirectColor4("color1", this.color1);
  57544. this._updateEffect.setDirectColor4("color2", this.color2);
  57545. }
  57546. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57547. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57548. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57549. this._updateEffect.setVector3("gravity", this.gravity);
  57550. if (this._sizeGradientsTexture) {
  57551. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57552. }
  57553. if (this.particleEmitterType) {
  57554. this.particleEmitterType.applyToShader(this._updateEffect);
  57555. }
  57556. var emitterWM;
  57557. if (this.emitter.position) {
  57558. var emitterMesh = this.emitter;
  57559. emitterWM = emitterMesh.getWorldMatrix();
  57560. }
  57561. else {
  57562. var emitterPosition = this.emitter;
  57563. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57564. }
  57565. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57566. // Bind source VAO
  57567. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57568. // Update
  57569. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57570. this._engine.setRasterizerState(false);
  57571. this._engine.beginTransformFeedback();
  57572. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57573. this._engine.endTransformFeedback();
  57574. this._engine.setRasterizerState(true);
  57575. this._engine.bindTransformFeedbackBuffer(null);
  57576. if (!preWarm) {
  57577. // Enable render effect
  57578. this._engine.enableEffect(this._renderEffect);
  57579. var viewMatrix = this._scene.getViewMatrix();
  57580. this._renderEffect.setMatrix("view", viewMatrix);
  57581. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57582. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57583. if (this._colorGradientsTexture) {
  57584. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57585. }
  57586. else {
  57587. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57588. }
  57589. if (this._scene.clipPlane) {
  57590. var clipPlane = this._scene.clipPlane;
  57591. var invView = viewMatrix.clone();
  57592. invView.invert();
  57593. this._renderEffect.setMatrix("invView", invView);
  57594. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57595. }
  57596. // Draw order
  57597. switch (this.blendMode) {
  57598. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57599. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57600. break;
  57601. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57602. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57603. break;
  57604. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57605. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57606. break;
  57607. }
  57608. if (this.forceDepthWrite) {
  57609. this._engine.setDepthWrite(true);
  57610. }
  57611. // Bind source VAO
  57612. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57613. // Render
  57614. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57615. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57616. }
  57617. // Switch VAOs
  57618. this._targetIndex++;
  57619. if (this._targetIndex === 2) {
  57620. this._targetIndex = 0;
  57621. }
  57622. // Switch buffers
  57623. var tmpBuffer = this._sourceBuffer;
  57624. this._sourceBuffer = this._targetBuffer;
  57625. this._targetBuffer = tmpBuffer;
  57626. return this._currentActiveCount;
  57627. };
  57628. /**
  57629. * Rebuilds the particle system
  57630. */
  57631. GPUParticleSystem.prototype.rebuild = function () {
  57632. this._initialize(true);
  57633. };
  57634. GPUParticleSystem.prototype._releaseBuffers = function () {
  57635. if (this._buffer0) {
  57636. this._buffer0.dispose();
  57637. this._buffer0 = null;
  57638. }
  57639. if (this._buffer1) {
  57640. this._buffer1.dispose();
  57641. this._buffer1 = null;
  57642. }
  57643. if (this._spriteBuffer) {
  57644. this._spriteBuffer.dispose();
  57645. this._spriteBuffer = null;
  57646. }
  57647. };
  57648. GPUParticleSystem.prototype._releaseVAOs = function () {
  57649. if (!this._updateVAO) {
  57650. return;
  57651. }
  57652. for (var index = 0; index < this._updateVAO.length; index++) {
  57653. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57654. }
  57655. this._updateVAO = [];
  57656. for (var index = 0; index < this._renderVAO.length; index++) {
  57657. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57658. }
  57659. this._renderVAO = [];
  57660. };
  57661. /**
  57662. * Disposes the particle system and free the associated resources
  57663. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57664. */
  57665. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57666. if (disposeTexture === void 0) { disposeTexture = true; }
  57667. var index = this._scene.particleSystems.indexOf(this);
  57668. if (index > -1) {
  57669. this._scene.particleSystems.splice(index, 1);
  57670. }
  57671. this._releaseBuffers();
  57672. this._releaseVAOs();
  57673. if (this._colorGradientsTexture) {
  57674. this._colorGradientsTexture.dispose();
  57675. this._colorGradientsTexture = null;
  57676. }
  57677. if (this._sizeGradientsTexture) {
  57678. this._sizeGradientsTexture.dispose();
  57679. this._sizeGradientsTexture = null;
  57680. }
  57681. if (this._randomTexture) {
  57682. this._randomTexture.dispose();
  57683. this._randomTexture = null;
  57684. }
  57685. if (this._randomTexture2) {
  57686. this._randomTexture2.dispose();
  57687. this._randomTexture2 = null;
  57688. }
  57689. if (disposeTexture && this.particleTexture) {
  57690. this.particleTexture.dispose();
  57691. this.particleTexture = null;
  57692. }
  57693. // Callback
  57694. this.onDisposeObservable.notifyObservers(this);
  57695. this.onDisposeObservable.clear();
  57696. };
  57697. /**
  57698. * Clones the particle system.
  57699. * @param name The name of the cloned object
  57700. * @param newEmitter The new emitter to use
  57701. * @returns the cloned particle system
  57702. */
  57703. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57704. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57705. BABYLON.Tools.DeepCopy(this, result);
  57706. if (newEmitter === undefined) {
  57707. newEmitter = this.emitter;
  57708. }
  57709. result.emitter = newEmitter;
  57710. if (this.particleTexture) {
  57711. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57712. }
  57713. return result;
  57714. };
  57715. /**
  57716. * Serializes the particle system to a JSON object.
  57717. * @returns the JSON object
  57718. */
  57719. GPUParticleSystem.prototype.serialize = function () {
  57720. var serializationObject = {};
  57721. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57722. return serializationObject;
  57723. };
  57724. /**
  57725. * Parses a JSON object to create a GPU particle system.
  57726. * @param parsedParticleSystem The JSON object to parse
  57727. * @param scene The scene to create the particle system in
  57728. * @param rootUrl The root url to use to load external dependencies like texture
  57729. * @returns the parsed GPU particle system
  57730. */
  57731. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57732. var name = parsedParticleSystem.name;
  57733. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57734. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57735. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57736. return particleSystem;
  57737. };
  57738. return GPUParticleSystem;
  57739. }());
  57740. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57741. })(BABYLON || (BABYLON = {}));
  57742. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57743. var BABYLON;
  57744. (function (BABYLON) {
  57745. /**
  57746. * Represents one particle of a solid particle system.
  57747. */
  57748. var SolidParticle = /** @class */ (function () {
  57749. /**
  57750. * Creates a Solid Particle object.
  57751. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57752. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57753. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57754. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57755. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57756. * @param shapeId (integer) is the model shape identifier in the SPS.
  57757. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57758. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57759. */
  57760. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57761. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57762. /**
  57763. * particle global index
  57764. */
  57765. this.idx = 0;
  57766. /**
  57767. * The color of the particle
  57768. */
  57769. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57770. /**
  57771. * The world space position of the particle.
  57772. */
  57773. this.position = BABYLON.Vector3.Zero();
  57774. /**
  57775. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57776. */
  57777. this.rotation = BABYLON.Vector3.Zero();
  57778. /**
  57779. * The scaling of the particle.
  57780. */
  57781. this.scaling = BABYLON.Vector3.One();
  57782. /**
  57783. * The uvs of the particle.
  57784. */
  57785. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57786. /**
  57787. * The current speed of the particle.
  57788. */
  57789. this.velocity = BABYLON.Vector3.Zero();
  57790. /**
  57791. * The pivot point in the particle local space.
  57792. */
  57793. this.pivot = BABYLON.Vector3.Zero();
  57794. /**
  57795. * Must the particle be translated from its pivot point in its local space ?
  57796. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57797. * Default : false
  57798. */
  57799. this.translateFromPivot = false;
  57800. /**
  57801. * Is the particle active or not ?
  57802. */
  57803. this.alive = true;
  57804. /**
  57805. * Is the particle visible or not ?
  57806. */
  57807. this.isVisible = true;
  57808. /**
  57809. * Index of this particle in the global "positions" array (Internal use)
  57810. */
  57811. this._pos = 0;
  57812. /**
  57813. * Index of this particle in the global "indices" array (Internal use)
  57814. */
  57815. this._ind = 0;
  57816. /**
  57817. * ModelShape id of this particle
  57818. */
  57819. this.shapeId = 0;
  57820. /**
  57821. * Index of the particle in its shape id (Internal use)
  57822. */
  57823. this.idxInShape = 0;
  57824. /**
  57825. * Still set as invisible in order to skip useless computations (Internal use)
  57826. */
  57827. this._stillInvisible = false;
  57828. /**
  57829. * Last computed particle rotation matrix
  57830. */
  57831. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57832. /**
  57833. * Parent particle Id, if any.
  57834. * Default null.
  57835. */
  57836. this.parentId = null;
  57837. /**
  57838. * Internal global position in the SPS.
  57839. */
  57840. this._globalPosition = BABYLON.Vector3.Zero();
  57841. this.idx = particleIndex;
  57842. this._pos = positionIndex;
  57843. this._ind = indiceIndex;
  57844. this._model = model;
  57845. this.shapeId = shapeId;
  57846. this.idxInShape = idxInShape;
  57847. this._sps = sps;
  57848. if (modelBoundingInfo) {
  57849. this._modelBoundingInfo = modelBoundingInfo;
  57850. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57851. }
  57852. }
  57853. Object.defineProperty(SolidParticle.prototype, "scale", {
  57854. /**
  57855. * Legacy support, changed scale to scaling
  57856. */
  57857. get: function () {
  57858. return this.scaling;
  57859. },
  57860. /**
  57861. * Legacy support, changed scale to scaling
  57862. */
  57863. set: function (scale) {
  57864. this.scaling = scale;
  57865. },
  57866. enumerable: true,
  57867. configurable: true
  57868. });
  57869. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57870. /**
  57871. * Legacy support, changed quaternion to rotationQuaternion
  57872. */
  57873. get: function () {
  57874. return this.rotationQuaternion;
  57875. },
  57876. /**
  57877. * Legacy support, changed quaternion to rotationQuaternion
  57878. */
  57879. set: function (q) {
  57880. this.rotationQuaternion = q;
  57881. },
  57882. enumerable: true,
  57883. configurable: true
  57884. });
  57885. /**
  57886. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57887. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57888. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57889. * @returns true if it intersects
  57890. */
  57891. SolidParticle.prototype.intersectsMesh = function (target) {
  57892. if (!this._boundingInfo || !target._boundingInfo) {
  57893. return false;
  57894. }
  57895. if (this._sps._bSphereOnly) {
  57896. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57897. }
  57898. return this._boundingInfo.intersects(target._boundingInfo, false);
  57899. };
  57900. return SolidParticle;
  57901. }());
  57902. BABYLON.SolidParticle = SolidParticle;
  57903. /**
  57904. * Represents the shape of the model used by one particle of a solid particle system.
  57905. * SPS internal tool, don't use it manually.
  57906. */
  57907. var ModelShape = /** @class */ (function () {
  57908. /**
  57909. * 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.
  57910. * SPS internal tool, don't use it manually.
  57911. * @hidden
  57912. */
  57913. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57914. /**
  57915. * length of the shape in the model indices array (internal use)
  57916. */
  57917. this._indicesLength = 0;
  57918. this.shapeID = id;
  57919. this._shape = shape;
  57920. this._indicesLength = indicesLength;
  57921. this._shapeUV = shapeUV;
  57922. this._positionFunction = posFunction;
  57923. this._vertexFunction = vtxFunction;
  57924. }
  57925. return ModelShape;
  57926. }());
  57927. BABYLON.ModelShape = ModelShape;
  57928. /**
  57929. * Represents a Depth Sorted Particle in the solid particle system.
  57930. */
  57931. var DepthSortedParticle = /** @class */ (function () {
  57932. function DepthSortedParticle() {
  57933. /**
  57934. * Index of the particle in the "indices" array
  57935. */
  57936. this.ind = 0;
  57937. /**
  57938. * Length of the particle shape in the "indices" array
  57939. */
  57940. this.indicesLength = 0;
  57941. /**
  57942. * Squared distance from the particle to the camera
  57943. */
  57944. this.sqDistance = 0.0;
  57945. }
  57946. return DepthSortedParticle;
  57947. }());
  57948. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57949. })(BABYLON || (BABYLON = {}));
  57950. //# sourceMappingURL=babylon.solidParticle.js.map
  57951. var BABYLON;
  57952. (function (BABYLON) {
  57953. /**
  57954. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57955. *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.
  57956. * The SPS is also a particle system. It provides some methods to manage the particles.
  57957. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57958. *
  57959. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57960. */
  57961. var SolidParticleSystem = /** @class */ (function () {
  57962. /**
  57963. * Creates a SPS (Solid Particle System) object.
  57964. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57965. * @param scene (Scene) is the scene in which the SPS is added.
  57966. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57967. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57968. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57969. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57970. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57971. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57972. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57973. */
  57974. function SolidParticleSystem(name, scene, options) {
  57975. /**
  57976. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57977. * Example : var p = SPS.particles[i];
  57978. */
  57979. this.particles = new Array();
  57980. /**
  57981. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57982. */
  57983. this.nbParticles = 0;
  57984. /**
  57985. * If the particles must ever face the camera (default false). Useful for planar particles.
  57986. */
  57987. this.billboard = false;
  57988. /**
  57989. * Recompute normals when adding a shape
  57990. */
  57991. this.recomputeNormals = true;
  57992. /**
  57993. * This a counter ofr your own usage. It's not set by any SPS functions.
  57994. */
  57995. this.counter = 0;
  57996. /**
  57997. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57998. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57999. */
  58000. this.vars = {};
  58001. /**
  58002. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58003. */
  58004. this._bSphereOnly = false;
  58005. /**
  58006. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58007. */
  58008. this._bSphereRadiusFactor = 1.0;
  58009. this._positions = new Array();
  58010. this._indices = new Array();
  58011. this._normals = new Array();
  58012. this._colors = new Array();
  58013. this._uvs = new Array();
  58014. this._index = 0; // indices index
  58015. this._updatable = true;
  58016. this._pickable = false;
  58017. this._isVisibilityBoxLocked = false;
  58018. this._alwaysVisible = false;
  58019. this._depthSort = false;
  58020. this._shapeCounter = 0;
  58021. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58022. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58023. this._computeParticleColor = true;
  58024. this._computeParticleTexture = true;
  58025. this._computeParticleRotation = true;
  58026. this._computeParticleVertex = false;
  58027. this._computeBoundingBox = false;
  58028. this._depthSortParticles = true;
  58029. this._cam_axisZ = BABYLON.Vector3.Zero();
  58030. this._cam_axisY = BABYLON.Vector3.Zero();
  58031. this._cam_axisX = BABYLON.Vector3.Zero();
  58032. this._axisZ = BABYLON.Axis.Z;
  58033. this._camDir = BABYLON.Vector3.Zero();
  58034. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58035. this._rotMatrix = new BABYLON.Matrix();
  58036. this._invertMatrix = new BABYLON.Matrix();
  58037. this._rotated = BABYLON.Vector3.Zero();
  58038. this._quaternion = new BABYLON.Quaternion();
  58039. this._vertex = BABYLON.Vector3.Zero();
  58040. this._normal = BABYLON.Vector3.Zero();
  58041. this._yaw = 0.0;
  58042. this._pitch = 0.0;
  58043. this._roll = 0.0;
  58044. this._halfroll = 0.0;
  58045. this._halfpitch = 0.0;
  58046. this._halfyaw = 0.0;
  58047. this._sinRoll = 0.0;
  58048. this._cosRoll = 0.0;
  58049. this._sinPitch = 0.0;
  58050. this._cosPitch = 0.0;
  58051. this._sinYaw = 0.0;
  58052. this._cosYaw = 0.0;
  58053. this._mustUnrotateFixedNormals = false;
  58054. this._minimum = BABYLON.Vector3.Zero();
  58055. this._maximum = BABYLON.Vector3.Zero();
  58056. this._minBbox = BABYLON.Vector3.Zero();
  58057. this._maxBbox = BABYLON.Vector3.Zero();
  58058. this._particlesIntersect = false;
  58059. this._depthSortFunction = function (p1, p2) {
  58060. return (p2.sqDistance - p1.sqDistance);
  58061. };
  58062. this._needs32Bits = false;
  58063. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58064. this._scaledPivot = BABYLON.Vector3.Zero();
  58065. this._particleHasParent = false;
  58066. this.name = name;
  58067. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58068. this._camera = scene.activeCamera;
  58069. this._pickable = options ? options.isPickable : false;
  58070. this._depthSort = options ? options.enableDepthSort : false;
  58071. this._particlesIntersect = options ? options.particleIntersection : false;
  58072. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58073. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58074. if (options && options.updatable !== undefined) {
  58075. this._updatable = options.updatable;
  58076. }
  58077. else {
  58078. this._updatable = true;
  58079. }
  58080. if (this._pickable) {
  58081. this.pickedParticles = [];
  58082. }
  58083. if (this._depthSort) {
  58084. this.depthSortedParticles = [];
  58085. }
  58086. }
  58087. /**
  58088. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58089. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58090. * @returns the created mesh
  58091. */
  58092. SolidParticleSystem.prototype.buildMesh = function () {
  58093. if (this.nbParticles === 0) {
  58094. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58095. this.addShape(triangle, 1);
  58096. triangle.dispose();
  58097. }
  58098. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58099. this._positions32 = new Float32Array(this._positions);
  58100. this._uvs32 = new Float32Array(this._uvs);
  58101. this._colors32 = new Float32Array(this._colors);
  58102. if (this.recomputeNormals) {
  58103. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58104. }
  58105. this._normals32 = new Float32Array(this._normals);
  58106. this._fixedNormal32 = new Float32Array(this._normals);
  58107. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58108. this._unrotateFixedNormals();
  58109. }
  58110. var vertexData = new BABYLON.VertexData();
  58111. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58112. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58113. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58114. if (this._uvs32.length > 0) {
  58115. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58116. }
  58117. if (this._colors32.length > 0) {
  58118. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58119. }
  58120. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58121. vertexData.applyToMesh(mesh, this._updatable);
  58122. this.mesh = mesh;
  58123. this.mesh.isPickable = this._pickable;
  58124. // free memory
  58125. if (!this._depthSort) {
  58126. this._indices = null;
  58127. }
  58128. this._positions = null;
  58129. this._normals = null;
  58130. this._uvs = null;
  58131. this._colors = null;
  58132. if (!this._updatable) {
  58133. this.particles.length = 0;
  58134. }
  58135. return mesh;
  58136. };
  58137. /**
  58138. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58139. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58140. * Thus the particles generated from `digest()` have their property `position` set yet.
  58141. * @param mesh ( Mesh ) is the mesh to be digested
  58142. * @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
  58143. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58144. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58145. * @returns the current SPS
  58146. */
  58147. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58148. var size = (options && options.facetNb) || 1;
  58149. var number = (options && options.number) || 0;
  58150. var delta = (options && options.delta) || 0;
  58151. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58152. var meshInd = mesh.getIndices();
  58153. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58154. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58155. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58156. var f = 0; // facet counter
  58157. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58158. // compute size from number
  58159. if (number) {
  58160. number = (number > totalFacets) ? totalFacets : number;
  58161. size = Math.round(totalFacets / number);
  58162. delta = 0;
  58163. }
  58164. else {
  58165. size = (size > totalFacets) ? totalFacets : size;
  58166. }
  58167. var facetPos = []; // submesh positions
  58168. var facetInd = []; // submesh indices
  58169. var facetUV = []; // submesh UV
  58170. var facetCol = []; // submesh colors
  58171. var barycenter = BABYLON.Vector3.Zero();
  58172. var sizeO = size;
  58173. while (f < totalFacets) {
  58174. size = sizeO + Math.floor((1 + delta) * Math.random());
  58175. if (f > totalFacets - size) {
  58176. size = totalFacets - f;
  58177. }
  58178. // reset temp arrays
  58179. facetPos.length = 0;
  58180. facetInd.length = 0;
  58181. facetUV.length = 0;
  58182. facetCol.length = 0;
  58183. // iterate over "size" facets
  58184. var fi = 0;
  58185. for (var j = f * 3; j < (f + size) * 3; j++) {
  58186. facetInd.push(fi);
  58187. var i = meshInd[j];
  58188. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58189. if (meshUV) {
  58190. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58191. }
  58192. if (meshCol) {
  58193. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58194. }
  58195. fi++;
  58196. }
  58197. // create a model shape for each single particle
  58198. var idx = this.nbParticles;
  58199. var shape = this._posToShape(facetPos);
  58200. var shapeUV = this._uvsToShapeUV(facetUV);
  58201. // compute the barycenter of the shape
  58202. var v;
  58203. for (v = 0; v < shape.length; v++) {
  58204. barycenter.addInPlace(shape[v]);
  58205. }
  58206. barycenter.scaleInPlace(1 / shape.length);
  58207. // shift the shape from its barycenter to the origin
  58208. for (v = 0; v < shape.length; v++) {
  58209. shape[v].subtractInPlace(barycenter);
  58210. }
  58211. var bInfo;
  58212. if (this._particlesIntersect) {
  58213. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58214. }
  58215. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58216. // add the particle in the SPS
  58217. var currentPos = this._positions.length;
  58218. var currentInd = this._indices.length;
  58219. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58220. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58221. // initialize the particle position
  58222. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58223. this._index += shape.length;
  58224. idx++;
  58225. this.nbParticles++;
  58226. this._shapeCounter++;
  58227. f += size;
  58228. }
  58229. return this;
  58230. };
  58231. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58232. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58233. var index = 0;
  58234. var idx = 0;
  58235. for (var p = 0; p < this.particles.length; p++) {
  58236. this._particle = this.particles[p];
  58237. this._shape = this._particle._model._shape;
  58238. if (this._particle.rotationQuaternion) {
  58239. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58240. }
  58241. else {
  58242. this._yaw = this._particle.rotation.y;
  58243. this._pitch = this._particle.rotation.x;
  58244. this._roll = this._particle.rotation.z;
  58245. this._quaternionRotationYPR();
  58246. }
  58247. this._quaternionToRotationMatrix();
  58248. this._rotMatrix.invertToRef(this._invertMatrix);
  58249. for (var pt = 0; pt < this._shape.length; pt++) {
  58250. idx = index + pt * 3;
  58251. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58252. this._fixedNormal32[idx] = this._normal.x;
  58253. this._fixedNormal32[idx + 1] = this._normal.y;
  58254. this._fixedNormal32[idx + 2] = this._normal.z;
  58255. }
  58256. index = idx + 3;
  58257. }
  58258. };
  58259. //reset copy
  58260. SolidParticleSystem.prototype._resetCopy = function () {
  58261. this._copy.position.x = 0;
  58262. this._copy.position.y = 0;
  58263. this._copy.position.z = 0;
  58264. this._copy.rotation.x = 0;
  58265. this._copy.rotation.y = 0;
  58266. this._copy.rotation.z = 0;
  58267. this._copy.rotationQuaternion = null;
  58268. this._copy.scaling.x = 1.0;
  58269. this._copy.scaling.y = 1.0;
  58270. this._copy.scaling.z = 1.0;
  58271. this._copy.uvs.x = 0;
  58272. this._copy.uvs.y = 0;
  58273. this._copy.uvs.z = 1.0;
  58274. this._copy.uvs.w = 1.0;
  58275. this._copy.color = null;
  58276. this._copy.translateFromPivot = false;
  58277. };
  58278. // _meshBuilder : inserts the shape model in the global SPS mesh
  58279. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58280. var i;
  58281. var u = 0;
  58282. var c = 0;
  58283. var n = 0;
  58284. this._resetCopy();
  58285. if (options && options.positionFunction) { // call to custom positionFunction
  58286. options.positionFunction(this._copy, idx, idxInShape);
  58287. this._mustUnrotateFixedNormals = true;
  58288. }
  58289. if (this._copy.rotationQuaternion) {
  58290. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58291. }
  58292. else {
  58293. this._yaw = this._copy.rotation.y;
  58294. this._pitch = this._copy.rotation.x;
  58295. this._roll = this._copy.rotation.z;
  58296. this._quaternionRotationYPR();
  58297. }
  58298. this._quaternionToRotationMatrix();
  58299. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58300. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58301. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58302. if (this._copy.translateFromPivot) {
  58303. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58304. }
  58305. else {
  58306. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58307. }
  58308. for (i = 0; i < shape.length; i++) {
  58309. this._vertex.x = shape[i].x;
  58310. this._vertex.y = shape[i].y;
  58311. this._vertex.z = shape[i].z;
  58312. if (options && options.vertexFunction) {
  58313. options.vertexFunction(this._copy, this._vertex, i);
  58314. }
  58315. this._vertex.x *= this._copy.scaling.x;
  58316. this._vertex.y *= this._copy.scaling.y;
  58317. this._vertex.z *= this._copy.scaling.z;
  58318. this._vertex.x -= this._scaledPivot.x;
  58319. this._vertex.y -= this._scaledPivot.y;
  58320. this._vertex.z -= this._scaledPivot.z;
  58321. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58322. this._rotated.addInPlace(this._pivotBackTranslation);
  58323. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58324. if (meshUV) {
  58325. 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);
  58326. u += 2;
  58327. }
  58328. if (this._copy.color) {
  58329. this._color = this._copy.color;
  58330. }
  58331. else if (meshCol && meshCol[c] !== undefined) {
  58332. this._color.r = meshCol[c];
  58333. this._color.g = meshCol[c + 1];
  58334. this._color.b = meshCol[c + 2];
  58335. this._color.a = meshCol[c + 3];
  58336. }
  58337. else {
  58338. this._color.r = 1.0;
  58339. this._color.g = 1.0;
  58340. this._color.b = 1.0;
  58341. this._color.a = 1.0;
  58342. }
  58343. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58344. c += 4;
  58345. if (!this.recomputeNormals && meshNor) {
  58346. this._normal.x = meshNor[n];
  58347. this._normal.y = meshNor[n + 1];
  58348. this._normal.z = meshNor[n + 2];
  58349. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58350. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58351. n += 3;
  58352. }
  58353. }
  58354. for (i = 0; i < meshInd.length; i++) {
  58355. var current_ind = p + meshInd[i];
  58356. indices.push(current_ind);
  58357. if (current_ind > 65535) {
  58358. this._needs32Bits = true;
  58359. }
  58360. }
  58361. if (this._pickable) {
  58362. var nbfaces = meshInd.length / 3;
  58363. for (i = 0; i < nbfaces; i++) {
  58364. this.pickedParticles.push({ idx: idx, faceId: i });
  58365. }
  58366. }
  58367. if (this._depthSort) {
  58368. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58369. }
  58370. return this._copy;
  58371. };
  58372. // returns a shape array from positions array
  58373. SolidParticleSystem.prototype._posToShape = function (positions) {
  58374. var shape = [];
  58375. for (var i = 0; i < positions.length; i += 3) {
  58376. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58377. }
  58378. return shape;
  58379. };
  58380. // returns a shapeUV array from a Vector4 uvs
  58381. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58382. var shapeUV = [];
  58383. if (uvs) {
  58384. for (var i = 0; i < uvs.length; i++)
  58385. shapeUV.push(uvs[i]);
  58386. }
  58387. return shapeUV;
  58388. };
  58389. // adds a new particle object in the particles array
  58390. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58391. if (bInfo === void 0) { bInfo = null; }
  58392. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58393. this.particles.push(sp);
  58394. return sp;
  58395. };
  58396. /**
  58397. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58398. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58399. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58400. * @param nb (positive integer) the number of particles to be created from this model
  58401. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58402. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58403. * @returns the number of shapes in the system
  58404. */
  58405. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58406. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58407. var meshInd = mesh.getIndices();
  58408. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58409. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58410. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58411. var bbInfo;
  58412. if (this._particlesIntersect) {
  58413. bbInfo = mesh.getBoundingInfo();
  58414. }
  58415. var shape = this._posToShape(meshPos);
  58416. var shapeUV = this._uvsToShapeUV(meshUV);
  58417. var posfunc = options ? options.positionFunction : null;
  58418. var vtxfunc = options ? options.vertexFunction : null;
  58419. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58420. // particles
  58421. var sp;
  58422. var currentCopy;
  58423. var idx = this.nbParticles;
  58424. for (var i = 0; i < nb; i++) {
  58425. var currentPos = this._positions.length;
  58426. var currentInd = this._indices.length;
  58427. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58428. if (this._updatable) {
  58429. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58430. sp.position.copyFrom(currentCopy.position);
  58431. sp.rotation.copyFrom(currentCopy.rotation);
  58432. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58433. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58434. }
  58435. if (currentCopy.color && sp.color) {
  58436. sp.color.copyFrom(currentCopy.color);
  58437. }
  58438. sp.scaling.copyFrom(currentCopy.scaling);
  58439. sp.uvs.copyFrom(currentCopy.uvs);
  58440. }
  58441. this._index += shape.length;
  58442. idx++;
  58443. }
  58444. this.nbParticles += nb;
  58445. this._shapeCounter++;
  58446. return this._shapeCounter - 1;
  58447. };
  58448. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58449. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58450. this._resetCopy();
  58451. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58452. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58453. }
  58454. if (this._copy.rotationQuaternion) {
  58455. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58456. }
  58457. else {
  58458. this._yaw = this._copy.rotation.y;
  58459. this._pitch = this._copy.rotation.x;
  58460. this._roll = this._copy.rotation.z;
  58461. this._quaternionRotationYPR();
  58462. }
  58463. this._quaternionToRotationMatrix();
  58464. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58465. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58466. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58467. if (this._copy.translateFromPivot) {
  58468. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58469. }
  58470. else {
  58471. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58472. }
  58473. this._shape = particle._model._shape;
  58474. for (var pt = 0; pt < this._shape.length; pt++) {
  58475. this._vertex.x = this._shape[pt].x;
  58476. this._vertex.y = this._shape[pt].y;
  58477. this._vertex.z = this._shape[pt].z;
  58478. if (particle._model._vertexFunction) {
  58479. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58480. }
  58481. this._vertex.x *= this._copy.scaling.x;
  58482. this._vertex.y *= this._copy.scaling.y;
  58483. this._vertex.z *= this._copy.scaling.z;
  58484. this._vertex.x -= this._scaledPivot.x;
  58485. this._vertex.y -= this._scaledPivot.y;
  58486. this._vertex.z -= this._scaledPivot.z;
  58487. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58488. this._rotated.addInPlace(this._pivotBackTranslation);
  58489. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58490. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58491. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58492. }
  58493. particle.position.x = 0.0;
  58494. particle.position.y = 0.0;
  58495. particle.position.z = 0.0;
  58496. particle.rotation.x = 0.0;
  58497. particle.rotation.y = 0.0;
  58498. particle.rotation.z = 0.0;
  58499. particle.rotationQuaternion = null;
  58500. particle.scaling.x = 1.0;
  58501. particle.scaling.y = 1.0;
  58502. particle.scaling.z = 1.0;
  58503. particle.uvs.x = 0.0;
  58504. particle.uvs.y = 0.0;
  58505. particle.uvs.z = 1.0;
  58506. particle.uvs.w = 1.0;
  58507. particle.pivot.x = 0.0;
  58508. particle.pivot.y = 0.0;
  58509. particle.pivot.z = 0.0;
  58510. particle.translateFromPivot = false;
  58511. particle.parentId = null;
  58512. };
  58513. /**
  58514. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58515. * @returns the SPS.
  58516. */
  58517. SolidParticleSystem.prototype.rebuildMesh = function () {
  58518. for (var p = 0; p < this.particles.length; p++) {
  58519. this._rebuildParticle(this.particles[p]);
  58520. }
  58521. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58522. return this;
  58523. };
  58524. /**
  58525. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58526. * This method calls `updateParticle()` for each particle of the SPS.
  58527. * For an animated SPS, it is usually called within the render loop.
  58528. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58529. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58530. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58531. * @returns the SPS.
  58532. */
  58533. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58534. if (start === void 0) { start = 0; }
  58535. if (end === void 0) { end = this.nbParticles - 1; }
  58536. if (update === void 0) { update = true; }
  58537. if (!this._updatable) {
  58538. return this;
  58539. }
  58540. // custom beforeUpdate
  58541. this.beforeUpdateParticles(start, end, update);
  58542. this._cam_axisX.x = 1.0;
  58543. this._cam_axisX.y = 0.0;
  58544. this._cam_axisX.z = 0.0;
  58545. this._cam_axisY.x = 0.0;
  58546. this._cam_axisY.y = 1.0;
  58547. this._cam_axisY.z = 0.0;
  58548. this._cam_axisZ.x = 0.0;
  58549. this._cam_axisZ.y = 0.0;
  58550. this._cam_axisZ.z = 1.0;
  58551. // cases when the World Matrix is to be computed first
  58552. if (this.billboard || this._depthSort) {
  58553. this.mesh.computeWorldMatrix(true);
  58554. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58555. }
  58556. // if the particles will always face the camera
  58557. if (this.billboard) {
  58558. // compute the camera position and un-rotate it by the current mesh rotation
  58559. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58560. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58561. this._cam_axisZ.normalize();
  58562. // same for camera up vector extracted from the cam view matrix
  58563. var view = this._camera.getViewMatrix(true);
  58564. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58565. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58566. this._cam_axisY.normalize();
  58567. this._cam_axisX.normalize();
  58568. }
  58569. // if depthSort, compute the camera global position in the mesh local system
  58570. if (this._depthSort) {
  58571. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58572. }
  58573. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58574. var idx = 0; // current position index in the global array positions32
  58575. var index = 0; // position start index in the global array positions32 of the current particle
  58576. var colidx = 0; // current color index in the global array colors32
  58577. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58578. var uvidx = 0; // current uv index in the global array uvs32
  58579. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58580. var pt = 0; // current index in the particle model shape
  58581. if (this.mesh.isFacetDataEnabled) {
  58582. this._computeBoundingBox = true;
  58583. }
  58584. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58585. if (this._computeBoundingBox) {
  58586. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58587. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58588. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58589. }
  58590. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58591. if (this.mesh._boundingInfo) {
  58592. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58593. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58594. }
  58595. }
  58596. }
  58597. // particle loop
  58598. index = this.particles[start]._pos;
  58599. var vpos = (index / 3) | 0;
  58600. colorIndex = vpos * 4;
  58601. uvIndex = vpos * 2;
  58602. for (var p = start; p <= end; p++) {
  58603. this._particle = this.particles[p];
  58604. this._shape = this._particle._model._shape;
  58605. this._shapeUV = this._particle._model._shapeUV;
  58606. // call to custom user function to update the particle properties
  58607. this.updateParticle(this._particle);
  58608. // camera-particle distance for depth sorting
  58609. if (this._depthSort && this._depthSortParticles) {
  58610. var dsp = this.depthSortedParticles[p];
  58611. dsp.ind = this._particle._ind;
  58612. dsp.indicesLength = this._particle._model._indicesLength;
  58613. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58614. }
  58615. // skip the computations for inactive or already invisible particles
  58616. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58617. // increment indexes for the next particle
  58618. pt = this._shape.length;
  58619. index += pt * 3;
  58620. colorIndex += pt * 4;
  58621. uvIndex += pt * 2;
  58622. continue;
  58623. }
  58624. if (this._particle.isVisible) {
  58625. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58626. this._particleHasParent = (this._particle.parentId !== null);
  58627. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58628. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58629. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58630. // particle rotation matrix
  58631. if (this.billboard) {
  58632. this._particle.rotation.x = 0.0;
  58633. this._particle.rotation.y = 0.0;
  58634. }
  58635. if (this._computeParticleRotation || this.billboard) {
  58636. if (this._particle.rotationQuaternion) {
  58637. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58638. }
  58639. else {
  58640. this._yaw = this._particle.rotation.y;
  58641. this._pitch = this._particle.rotation.x;
  58642. this._roll = this._particle.rotation.z;
  58643. this._quaternionRotationYPR();
  58644. }
  58645. this._quaternionToRotationMatrix();
  58646. }
  58647. if (this._particleHasParent) {
  58648. this._parent = this.particles[this._particle.parentId];
  58649. 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];
  58650. 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];
  58651. 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];
  58652. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58653. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58654. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58655. if (this._computeParticleRotation || this.billboard) {
  58656. 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];
  58657. 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];
  58658. 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];
  58659. 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];
  58660. 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];
  58661. 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];
  58662. 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];
  58663. 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];
  58664. 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];
  58665. }
  58666. }
  58667. else {
  58668. this._particle._globalPosition.x = this._particle.position.x;
  58669. this._particle._globalPosition.y = this._particle.position.y;
  58670. this._particle._globalPosition.z = this._particle.position.z;
  58671. if (this._computeParticleRotation || this.billboard) {
  58672. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58673. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58674. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58675. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58676. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58677. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58678. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58679. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58680. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58681. }
  58682. }
  58683. if (this._particle.translateFromPivot) {
  58684. this._pivotBackTranslation.x = 0.0;
  58685. this._pivotBackTranslation.y = 0.0;
  58686. this._pivotBackTranslation.z = 0.0;
  58687. }
  58688. else {
  58689. this._pivotBackTranslation.x = this._scaledPivot.x;
  58690. this._pivotBackTranslation.y = this._scaledPivot.y;
  58691. this._pivotBackTranslation.z = this._scaledPivot.z;
  58692. }
  58693. // particle vertex loop
  58694. for (pt = 0; pt < this._shape.length; pt++) {
  58695. idx = index + pt * 3;
  58696. colidx = colorIndex + pt * 4;
  58697. uvidx = uvIndex + pt * 2;
  58698. this._vertex.x = this._shape[pt].x;
  58699. this._vertex.y = this._shape[pt].y;
  58700. this._vertex.z = this._shape[pt].z;
  58701. if (this._computeParticleVertex) {
  58702. this.updateParticleVertex(this._particle, this._vertex, pt);
  58703. }
  58704. // positions
  58705. this._vertex.x *= this._particle.scaling.x;
  58706. this._vertex.y *= this._particle.scaling.y;
  58707. this._vertex.z *= this._particle.scaling.z;
  58708. this._vertex.x -= this._scaledPivot.x;
  58709. this._vertex.y -= this._scaledPivot.y;
  58710. this._vertex.z -= this._scaledPivot.z;
  58711. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58712. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58713. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58714. this._rotated.x += this._pivotBackTranslation.x;
  58715. this._rotated.y += this._pivotBackTranslation.y;
  58716. this._rotated.z += this._pivotBackTranslation.z;
  58717. 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;
  58718. 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;
  58719. 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;
  58720. if (this._computeBoundingBox) {
  58721. if (this._positions32[idx] < this._minimum.x) {
  58722. this._minimum.x = this._positions32[idx];
  58723. }
  58724. if (this._positions32[idx] > this._maximum.x) {
  58725. this._maximum.x = this._positions32[idx];
  58726. }
  58727. if (this._positions32[idx + 1] < this._minimum.y) {
  58728. this._minimum.y = this._positions32[idx + 1];
  58729. }
  58730. if (this._positions32[idx + 1] > this._maximum.y) {
  58731. this._maximum.y = this._positions32[idx + 1];
  58732. }
  58733. if (this._positions32[idx + 2] < this._minimum.z) {
  58734. this._minimum.z = this._positions32[idx + 2];
  58735. }
  58736. if (this._positions32[idx + 2] > this._maximum.z) {
  58737. this._maximum.z = this._positions32[idx + 2];
  58738. }
  58739. }
  58740. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58741. if (!this._computeParticleVertex) {
  58742. this._normal.x = this._fixedNormal32[idx];
  58743. this._normal.y = this._fixedNormal32[idx + 1];
  58744. this._normal.z = this._fixedNormal32[idx + 2];
  58745. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58746. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58747. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58748. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58749. 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;
  58750. 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;
  58751. }
  58752. if (this._computeParticleColor && this._particle.color) {
  58753. this._colors32[colidx] = this._particle.color.r;
  58754. this._colors32[colidx + 1] = this._particle.color.g;
  58755. this._colors32[colidx + 2] = this._particle.color.b;
  58756. this._colors32[colidx + 3] = this._particle.color.a;
  58757. }
  58758. if (this._computeParticleTexture) {
  58759. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58760. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58761. }
  58762. }
  58763. }
  58764. // particle just set invisible : scaled to zero and positioned at the origin
  58765. else {
  58766. this._particle._stillInvisible = true; // mark the particle as invisible
  58767. for (pt = 0; pt < this._shape.length; pt++) {
  58768. idx = index + pt * 3;
  58769. colidx = colorIndex + pt * 4;
  58770. uvidx = uvIndex + pt * 2;
  58771. this._positions32[idx] = 0.0;
  58772. this._positions32[idx + 1] = 0.0;
  58773. this._positions32[idx + 2] = 0.0;
  58774. this._normals32[idx] = 0.0;
  58775. this._normals32[idx + 1] = 0.0;
  58776. this._normals32[idx + 2] = 0.0;
  58777. if (this._computeParticleColor && this._particle.color) {
  58778. this._colors32[colidx] = this._particle.color.r;
  58779. this._colors32[colidx + 1] = this._particle.color.g;
  58780. this._colors32[colidx + 2] = this._particle.color.b;
  58781. this._colors32[colidx + 3] = this._particle.color.a;
  58782. }
  58783. if (this._computeParticleTexture) {
  58784. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58785. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58786. }
  58787. }
  58788. }
  58789. // if the particle intersections must be computed : update the bbInfo
  58790. if (this._particlesIntersect) {
  58791. var bInfo = this._particle._boundingInfo;
  58792. var bBox = bInfo.boundingBox;
  58793. var bSphere = bInfo.boundingSphere;
  58794. if (!this._bSphereOnly) {
  58795. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58796. for (var b = 0; b < bBox.vectors.length; b++) {
  58797. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58798. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58799. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58800. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58801. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58802. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58803. 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;
  58804. 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;
  58805. 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;
  58806. }
  58807. bBox._update(this.mesh._worldMatrix);
  58808. }
  58809. // place and scale the particle bouding sphere in the SPS local system, then update it
  58810. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58811. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58812. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58813. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58814. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58815. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58816. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58817. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58818. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58819. 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));
  58820. bSphere._update(this.mesh._worldMatrix);
  58821. }
  58822. // increment indexes for the next particle
  58823. index = idx + 3;
  58824. colorIndex = colidx + 4;
  58825. uvIndex = uvidx + 2;
  58826. }
  58827. // if the VBO must be updated
  58828. if (update) {
  58829. if (this._computeParticleColor) {
  58830. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58831. }
  58832. if (this._computeParticleTexture) {
  58833. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58834. }
  58835. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58836. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58837. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58838. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58839. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58840. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58841. for (var i = 0; i < this._normals32.length; i++) {
  58842. this._fixedNormal32[i] = this._normals32[i];
  58843. }
  58844. }
  58845. if (!this.mesh.areNormalsFrozen) {
  58846. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58847. }
  58848. }
  58849. if (this._depthSort && this._depthSortParticles) {
  58850. this.depthSortedParticles.sort(this._depthSortFunction);
  58851. var dspl = this.depthSortedParticles.length;
  58852. var sorted = 0;
  58853. var lind = 0;
  58854. var sind = 0;
  58855. var sid = 0;
  58856. for (sorted = 0; sorted < dspl; sorted++) {
  58857. lind = this.depthSortedParticles[sorted].indicesLength;
  58858. sind = this.depthSortedParticles[sorted].ind;
  58859. for (var i = 0; i < lind; i++) {
  58860. this._indices32[sid] = this._indices[sind + i];
  58861. sid++;
  58862. }
  58863. }
  58864. this.mesh.updateIndices(this._indices32);
  58865. }
  58866. }
  58867. if (this._computeBoundingBox) {
  58868. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58869. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58870. }
  58871. this.afterUpdateParticles(start, end, update);
  58872. return this;
  58873. };
  58874. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58875. this._halfroll = this._roll * 0.5;
  58876. this._halfpitch = this._pitch * 0.5;
  58877. this._halfyaw = this._yaw * 0.5;
  58878. this._sinRoll = Math.sin(this._halfroll);
  58879. this._cosRoll = Math.cos(this._halfroll);
  58880. this._sinPitch = Math.sin(this._halfpitch);
  58881. this._cosPitch = Math.cos(this._halfpitch);
  58882. this._sinYaw = Math.sin(this._halfyaw);
  58883. this._cosYaw = Math.cos(this._halfyaw);
  58884. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58885. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58886. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58887. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58888. };
  58889. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58890. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58891. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58892. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58893. this._rotMatrix.m[3] = 0;
  58894. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58895. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58896. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58897. this._rotMatrix.m[7] = 0;
  58898. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58899. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58900. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58901. this._rotMatrix.m[11] = 0;
  58902. this._rotMatrix.m[12] = 0;
  58903. this._rotMatrix.m[13] = 0;
  58904. this._rotMatrix.m[14] = 0;
  58905. this._rotMatrix.m[15] = 1.0;
  58906. };
  58907. /**
  58908. * Disposes the SPS.
  58909. */
  58910. SolidParticleSystem.prototype.dispose = function () {
  58911. this.mesh.dispose();
  58912. this.vars = null;
  58913. // drop references to internal big arrays for the GC
  58914. this._positions = null;
  58915. this._indices = null;
  58916. this._normals = null;
  58917. this._uvs = null;
  58918. this._colors = null;
  58919. this._indices32 = null;
  58920. this._positions32 = null;
  58921. this._normals32 = null;
  58922. this._fixedNormal32 = null;
  58923. this._uvs32 = null;
  58924. this._colors32 = null;
  58925. this.pickedParticles = null;
  58926. };
  58927. /**
  58928. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58930. * @returns the SPS.
  58931. */
  58932. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58933. if (!this._isVisibilityBoxLocked) {
  58934. this.mesh.refreshBoundingInfo();
  58935. }
  58936. return this;
  58937. };
  58938. /**
  58939. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58940. * @param size the size (float) of the visibility box
  58941. * note : this doesn't lock the SPS mesh bounding box.
  58942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58943. */
  58944. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58945. var vis = size / 2;
  58946. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58947. };
  58948. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58949. /**
  58950. * Gets whether the SPS as always visible or not
  58951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58952. */
  58953. get: function () {
  58954. return this._alwaysVisible;
  58955. },
  58956. /**
  58957. * Sets the SPS as always visible or not
  58958. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58959. */
  58960. set: function (val) {
  58961. this._alwaysVisible = val;
  58962. this.mesh.alwaysSelectAsActiveMesh = val;
  58963. },
  58964. enumerable: true,
  58965. configurable: true
  58966. });
  58967. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58968. /**
  58969. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58970. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58971. */
  58972. get: function () {
  58973. return this._isVisibilityBoxLocked;
  58974. },
  58975. /**
  58976. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58978. */
  58979. set: function (val) {
  58980. this._isVisibilityBoxLocked = val;
  58981. var boundingInfo = this.mesh.getBoundingInfo();
  58982. boundingInfo.isLocked = val;
  58983. },
  58984. enumerable: true,
  58985. configurable: true
  58986. });
  58987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58988. /**
  58989. * Gets if `setParticles()` computes the particle rotations or not.
  58990. * Default value : true. The SPS is faster when it's set to false.
  58991. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58992. */
  58993. get: function () {
  58994. return this._computeParticleRotation;
  58995. },
  58996. /**
  58997. * Tells to `setParticles()` to compute the particle rotations or not.
  58998. * Default value : true. The SPS is faster when it's set to false.
  58999. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59000. */
  59001. set: function (val) {
  59002. this._computeParticleRotation = val;
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59008. /**
  59009. * Gets if `setParticles()` computes the particle colors or not.
  59010. * Default value : true. The SPS is faster when it's set to false.
  59011. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59012. */
  59013. get: function () {
  59014. return this._computeParticleColor;
  59015. },
  59016. /**
  59017. * Tells to `setParticles()` to compute the particle colors or not.
  59018. * Default value : true. The SPS is faster when it's set to false.
  59019. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59020. */
  59021. set: function (val) {
  59022. this._computeParticleColor = val;
  59023. },
  59024. enumerable: true,
  59025. configurable: true
  59026. });
  59027. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59028. /**
  59029. * Gets if `setParticles()` computes the particle textures or not.
  59030. * Default value : true. The SPS is faster when it's set to false.
  59031. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59032. */
  59033. get: function () {
  59034. return this._computeParticleTexture;
  59035. },
  59036. set: function (val) {
  59037. this._computeParticleTexture = val;
  59038. },
  59039. enumerable: true,
  59040. configurable: true
  59041. });
  59042. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59043. /**
  59044. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59045. * Default value : false. The SPS is faster when it's set to false.
  59046. * Note : the particle custom vertex positions aren't stored values.
  59047. */
  59048. get: function () {
  59049. return this._computeParticleVertex;
  59050. },
  59051. /**
  59052. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59053. * Default value : false. The SPS is faster when it's set to false.
  59054. * Note : the particle custom vertex positions aren't stored values.
  59055. */
  59056. set: function (val) {
  59057. this._computeParticleVertex = val;
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59063. /**
  59064. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59065. */
  59066. get: function () {
  59067. return this._computeBoundingBox;
  59068. },
  59069. /**
  59070. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59071. */
  59072. set: function (val) {
  59073. this._computeBoundingBox = val;
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59079. /**
  59080. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59081. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59082. * Default : `true`
  59083. */
  59084. get: function () {
  59085. return this._depthSortParticles;
  59086. },
  59087. /**
  59088. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59089. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59090. * Default : `true`
  59091. */
  59092. set: function (val) {
  59093. this._depthSortParticles = val;
  59094. },
  59095. enumerable: true,
  59096. configurable: true
  59097. });
  59098. // =======================================================================
  59099. // Particle behavior logic
  59100. // these following methods may be overwritten by the user to fit his needs
  59101. /**
  59102. * This function does nothing. It may be overwritten to set all the particle first values.
  59103. * The SPS doesn't call this function, you may have to call it by your own.
  59104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59105. */
  59106. SolidParticleSystem.prototype.initParticles = function () {
  59107. };
  59108. /**
  59109. * This function does nothing. It may be overwritten to recycle a particle.
  59110. * The SPS doesn't call this function, you may have to call it by your own.
  59111. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59112. * @param particle The particle to recycle
  59113. * @returns the recycled particle
  59114. */
  59115. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59116. return particle;
  59117. };
  59118. /**
  59119. * Updates a particle : this function should be overwritten by the user.
  59120. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59121. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59122. * @example : just set a particle position or velocity and recycle conditions
  59123. * @param particle The particle to update
  59124. * @returns the updated particle
  59125. */
  59126. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59127. return particle;
  59128. };
  59129. /**
  59130. * Updates a vertex of a particle : it can be overwritten by the user.
  59131. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59132. * @param particle the current particle
  59133. * @param vertex the current index of the current particle
  59134. * @param pt the index of the current vertex in the particle shape
  59135. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59136. * @example : just set a vertex particle position
  59137. * @returns the updated vertex
  59138. */
  59139. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59140. return vertex;
  59141. };
  59142. /**
  59143. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59144. * This does nothing and may be overwritten by the user.
  59145. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59146. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59147. * @param update the boolean update value actually passed to setParticles()
  59148. */
  59149. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59150. };
  59151. /**
  59152. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59153. * This will be passed three parameters.
  59154. * This does nothing and may be overwritten by the user.
  59155. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59156. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59157. * @param update the boolean update value actually passed to setParticles()
  59158. */
  59159. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59160. };
  59161. return SolidParticleSystem;
  59162. }());
  59163. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59164. })(BABYLON || (BABYLON = {}));
  59165. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59166. var BABYLON;
  59167. (function (BABYLON) {
  59168. var ShaderMaterial = /** @class */ (function (_super) {
  59169. __extends(ShaderMaterial, _super);
  59170. function ShaderMaterial(name, scene, shaderPath, options) {
  59171. var _this = _super.call(this, name, scene) || this;
  59172. _this._textures = {};
  59173. _this._textureArrays = {};
  59174. _this._floats = {};
  59175. _this._ints = {};
  59176. _this._floatsArrays = {};
  59177. _this._colors3 = {};
  59178. _this._colors3Arrays = {};
  59179. _this._colors4 = {};
  59180. _this._vectors2 = {};
  59181. _this._vectors3 = {};
  59182. _this._vectors4 = {};
  59183. _this._matrices = {};
  59184. _this._matrices3x3 = {};
  59185. _this._matrices2x2 = {};
  59186. _this._vectors2Arrays = {};
  59187. _this._vectors3Arrays = {};
  59188. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59189. _this._shaderPath = shaderPath;
  59190. options.needAlphaBlending = options.needAlphaBlending || false;
  59191. options.needAlphaTesting = options.needAlphaTesting || false;
  59192. options.attributes = options.attributes || ["position", "normal", "uv"];
  59193. options.uniforms = options.uniforms || ["worldViewProjection"];
  59194. options.uniformBuffers = options.uniformBuffers || [];
  59195. options.samplers = options.samplers || [];
  59196. options.defines = options.defines || [];
  59197. _this._options = options;
  59198. return _this;
  59199. }
  59200. ShaderMaterial.prototype.getClassName = function () {
  59201. return "ShaderMaterial";
  59202. };
  59203. ShaderMaterial.prototype.needAlphaBlending = function () {
  59204. return this._options.needAlphaBlending;
  59205. };
  59206. ShaderMaterial.prototype.needAlphaTesting = function () {
  59207. return this._options.needAlphaTesting;
  59208. };
  59209. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59210. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59211. this._options.uniforms.push(uniformName);
  59212. }
  59213. };
  59214. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59215. if (this._options.samplers.indexOf(name) === -1) {
  59216. this._options.samplers.push(name);
  59217. }
  59218. this._textures[name] = texture;
  59219. return this;
  59220. };
  59221. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59222. if (this._options.samplers.indexOf(name) === -1) {
  59223. this._options.samplers.push(name);
  59224. }
  59225. this._checkUniform(name);
  59226. this._textureArrays[name] = textures;
  59227. return this;
  59228. };
  59229. ShaderMaterial.prototype.setFloat = function (name, value) {
  59230. this._checkUniform(name);
  59231. this._floats[name] = value;
  59232. return this;
  59233. };
  59234. ShaderMaterial.prototype.setInt = function (name, value) {
  59235. this._checkUniform(name);
  59236. this._ints[name] = value;
  59237. return this;
  59238. };
  59239. ShaderMaterial.prototype.setFloats = function (name, value) {
  59240. this._checkUniform(name);
  59241. this._floatsArrays[name] = value;
  59242. return this;
  59243. };
  59244. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59245. this._checkUniform(name);
  59246. this._colors3[name] = value;
  59247. return this;
  59248. };
  59249. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59250. this._checkUniform(name);
  59251. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59252. color.toArray(arr, arr.length);
  59253. return arr;
  59254. }, []);
  59255. return this;
  59256. };
  59257. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59258. this._checkUniform(name);
  59259. this._colors4[name] = value;
  59260. return this;
  59261. };
  59262. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59263. this._checkUniform(name);
  59264. this._vectors2[name] = value;
  59265. return this;
  59266. };
  59267. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59268. this._checkUniform(name);
  59269. this._vectors3[name] = value;
  59270. return this;
  59271. };
  59272. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59273. this._checkUniform(name);
  59274. this._vectors4[name] = value;
  59275. return this;
  59276. };
  59277. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59278. this._checkUniform(name);
  59279. this._matrices[name] = value;
  59280. return this;
  59281. };
  59282. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59283. this._checkUniform(name);
  59284. this._matrices3x3[name] = value;
  59285. return this;
  59286. };
  59287. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59288. this._checkUniform(name);
  59289. this._matrices2x2[name] = value;
  59290. return this;
  59291. };
  59292. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59293. this._checkUniform(name);
  59294. this._vectors2Arrays[name] = value;
  59295. return this;
  59296. };
  59297. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59298. this._checkUniform(name);
  59299. this._vectors3Arrays[name] = value;
  59300. return this;
  59301. };
  59302. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59303. if (!mesh) {
  59304. return true;
  59305. }
  59306. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59307. return false;
  59308. }
  59309. return false;
  59310. };
  59311. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59312. var scene = this.getScene();
  59313. var engine = scene.getEngine();
  59314. if (!this.checkReadyOnEveryCall) {
  59315. if (this._renderId === scene.getRenderId()) {
  59316. if (this._checkCache(scene, mesh, useInstances)) {
  59317. return true;
  59318. }
  59319. }
  59320. }
  59321. // Instances
  59322. var defines = [];
  59323. var attribs = [];
  59324. var fallbacks = new BABYLON.EffectFallbacks();
  59325. if (useInstances) {
  59326. defines.push("#define INSTANCES");
  59327. }
  59328. for (var index = 0; index < this._options.defines.length; index++) {
  59329. defines.push(this._options.defines[index]);
  59330. }
  59331. for (var index = 0; index < this._options.attributes.length; index++) {
  59332. attribs.push(this._options.attributes[index]);
  59333. }
  59334. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59335. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59336. defines.push("#define VERTEXCOLOR");
  59337. }
  59338. // Bones
  59339. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59342. if (mesh.numBoneInfluencers > 4) {
  59343. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59344. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59345. }
  59346. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59347. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59348. fallbacks.addCPUSkinningFallback(0, mesh);
  59349. if (this._options.uniforms.indexOf("mBones") === -1) {
  59350. this._options.uniforms.push("mBones");
  59351. }
  59352. }
  59353. else {
  59354. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59355. }
  59356. // Textures
  59357. for (var name in this._textures) {
  59358. if (!this._textures[name].isReady()) {
  59359. return false;
  59360. }
  59361. }
  59362. // Alpha test
  59363. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59364. defines.push("#define ALPHATEST");
  59365. }
  59366. var previousEffect = this._effect;
  59367. var join = defines.join("\n");
  59368. this._effect = engine.createEffect(this._shaderPath, {
  59369. attributes: attribs,
  59370. uniformsNames: this._options.uniforms,
  59371. uniformBuffersNames: this._options.uniformBuffers,
  59372. samplers: this._options.samplers,
  59373. defines: join,
  59374. fallbacks: fallbacks,
  59375. onCompiled: this.onCompiled,
  59376. onError: this.onError
  59377. }, engine);
  59378. if (!this._effect.isReady()) {
  59379. return false;
  59380. }
  59381. if (previousEffect !== this._effect) {
  59382. scene.resetCachedMaterial();
  59383. }
  59384. this._renderId = scene.getRenderId();
  59385. return true;
  59386. };
  59387. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59388. var scene = this.getScene();
  59389. if (!this._effect) {
  59390. return;
  59391. }
  59392. if (this._options.uniforms.indexOf("world") !== -1) {
  59393. this._effect.setMatrix("world", world);
  59394. }
  59395. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59396. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59397. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59398. }
  59399. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59400. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59401. }
  59402. };
  59403. ShaderMaterial.prototype.bind = function (world, mesh) {
  59404. // Std values
  59405. this.bindOnlyWorldMatrix(world);
  59406. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59407. if (this._options.uniforms.indexOf("view") !== -1) {
  59408. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59409. }
  59410. if (this._options.uniforms.indexOf("projection") !== -1) {
  59411. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59412. }
  59413. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59414. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59415. }
  59416. // Bones
  59417. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59418. var name;
  59419. // Texture
  59420. for (name in this._textures) {
  59421. this._effect.setTexture(name, this._textures[name]);
  59422. }
  59423. // Texture arrays
  59424. for (name in this._textureArrays) {
  59425. this._effect.setTextureArray(name, this._textureArrays[name]);
  59426. }
  59427. // Int
  59428. for (name in this._ints) {
  59429. this._effect.setInt(name, this._ints[name]);
  59430. }
  59431. // Float
  59432. for (name in this._floats) {
  59433. this._effect.setFloat(name, this._floats[name]);
  59434. }
  59435. // Floats
  59436. for (name in this._floatsArrays) {
  59437. this._effect.setArray(name, this._floatsArrays[name]);
  59438. }
  59439. // Color3
  59440. for (name in this._colors3) {
  59441. this._effect.setColor3(name, this._colors3[name]);
  59442. }
  59443. for (name in this._colors3Arrays) {
  59444. this._effect.setArray3(name, this._colors3Arrays[name]);
  59445. }
  59446. // Color4
  59447. for (name in this._colors4) {
  59448. var color = this._colors4[name];
  59449. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59450. }
  59451. // Vector2
  59452. for (name in this._vectors2) {
  59453. this._effect.setVector2(name, this._vectors2[name]);
  59454. }
  59455. // Vector3
  59456. for (name in this._vectors3) {
  59457. this._effect.setVector3(name, this._vectors3[name]);
  59458. }
  59459. // Vector4
  59460. for (name in this._vectors4) {
  59461. this._effect.setVector4(name, this._vectors4[name]);
  59462. }
  59463. // Matrix
  59464. for (name in this._matrices) {
  59465. this._effect.setMatrix(name, this._matrices[name]);
  59466. }
  59467. // Matrix 3x3
  59468. for (name in this._matrices3x3) {
  59469. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59470. }
  59471. // Matrix 2x2
  59472. for (name in this._matrices2x2) {
  59473. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59474. }
  59475. // Vector2Array
  59476. for (name in this._vectors2Arrays) {
  59477. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59478. }
  59479. // Vector3Array
  59480. for (name in this._vectors3Arrays) {
  59481. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59482. }
  59483. }
  59484. this._afterBind(mesh);
  59485. };
  59486. ShaderMaterial.prototype.getActiveTextures = function () {
  59487. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59488. for (var name in this._textures) {
  59489. activeTextures.push(this._textures[name]);
  59490. }
  59491. for (var name in this._textureArrays) {
  59492. var array = this._textureArrays[name];
  59493. for (var index = 0; index < array.length; index++) {
  59494. activeTextures.push(array[index]);
  59495. }
  59496. }
  59497. return activeTextures;
  59498. };
  59499. ShaderMaterial.prototype.hasTexture = function (texture) {
  59500. if (_super.prototype.hasTexture.call(this, texture)) {
  59501. return true;
  59502. }
  59503. for (var name in this._textures) {
  59504. if (this._textures[name] === texture) {
  59505. return true;
  59506. }
  59507. }
  59508. for (var name in this._textureArrays) {
  59509. var array = this._textureArrays[name];
  59510. for (var index = 0; index < array.length; index++) {
  59511. if (array[index] === texture) {
  59512. return true;
  59513. }
  59514. }
  59515. }
  59516. return false;
  59517. };
  59518. ShaderMaterial.prototype.clone = function (name) {
  59519. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59520. return newShaderMaterial;
  59521. };
  59522. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59523. if (forceDisposeTextures) {
  59524. var name;
  59525. for (name in this._textures) {
  59526. this._textures[name].dispose();
  59527. }
  59528. for (name in this._textureArrays) {
  59529. var array = this._textureArrays[name];
  59530. for (var index = 0; index < array.length; index++) {
  59531. array[index].dispose();
  59532. }
  59533. }
  59534. }
  59535. this._textures = {};
  59536. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59537. };
  59538. ShaderMaterial.prototype.serialize = function () {
  59539. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59540. serializationObject.customType = "BABYLON.ShaderMaterial";
  59541. serializationObject.options = this._options;
  59542. serializationObject.shaderPath = this._shaderPath;
  59543. var name;
  59544. // Texture
  59545. serializationObject.textures = {};
  59546. for (name in this._textures) {
  59547. serializationObject.textures[name] = this._textures[name].serialize();
  59548. }
  59549. // Texture arrays
  59550. serializationObject.textureArrays = {};
  59551. for (name in this._textureArrays) {
  59552. serializationObject.textureArrays[name] = [];
  59553. var array = this._textureArrays[name];
  59554. for (var index = 0; index < array.length; index++) {
  59555. serializationObject.textureArrays[name].push(array[index].serialize());
  59556. }
  59557. }
  59558. // Float
  59559. serializationObject.floats = {};
  59560. for (name in this._floats) {
  59561. serializationObject.floats[name] = this._floats[name];
  59562. }
  59563. // Float s
  59564. serializationObject.FloatArrays = {};
  59565. for (name in this._floatsArrays) {
  59566. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59567. }
  59568. // Color3
  59569. serializationObject.colors3 = {};
  59570. for (name in this._colors3) {
  59571. serializationObject.colors3[name] = this._colors3[name].asArray();
  59572. }
  59573. // Color3 array
  59574. serializationObject.colors3Arrays = {};
  59575. for (name in this._colors3Arrays) {
  59576. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59577. }
  59578. // Color4
  59579. serializationObject.colors4 = {};
  59580. for (name in this._colors4) {
  59581. serializationObject.colors4[name] = this._colors4[name].asArray();
  59582. }
  59583. // Vector2
  59584. serializationObject.vectors2 = {};
  59585. for (name in this._vectors2) {
  59586. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59587. }
  59588. // Vector3
  59589. serializationObject.vectors3 = {};
  59590. for (name in this._vectors3) {
  59591. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59592. }
  59593. // Vector4
  59594. serializationObject.vectors4 = {};
  59595. for (name in this._vectors4) {
  59596. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59597. }
  59598. // Matrix
  59599. serializationObject.matrices = {};
  59600. for (name in this._matrices) {
  59601. serializationObject.matrices[name] = this._matrices[name].asArray();
  59602. }
  59603. // Matrix 3x3
  59604. serializationObject.matrices3x3 = {};
  59605. for (name in this._matrices3x3) {
  59606. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59607. }
  59608. // Matrix 2x2
  59609. serializationObject.matrices2x2 = {};
  59610. for (name in this._matrices2x2) {
  59611. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59612. }
  59613. // Vector2Array
  59614. serializationObject.vectors2Arrays = {};
  59615. for (name in this._vectors2Arrays) {
  59616. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59617. }
  59618. // Vector3Array
  59619. serializationObject.vectors3Arrays = {};
  59620. for (name in this._vectors3Arrays) {
  59621. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59622. }
  59623. return serializationObject;
  59624. };
  59625. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59626. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59627. var name;
  59628. // Texture
  59629. for (name in source.textures) {
  59630. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59631. }
  59632. // Texture arrays
  59633. for (name in source.textureArrays) {
  59634. var array = source.textureArrays[name];
  59635. var textureArray = new Array();
  59636. for (var index = 0; index < array.length; index++) {
  59637. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59638. }
  59639. material.setTextureArray(name, textureArray);
  59640. }
  59641. // Float
  59642. for (name in source.floats) {
  59643. material.setFloat(name, source.floats[name]);
  59644. }
  59645. // Float s
  59646. for (name in source.floatsArrays) {
  59647. material.setFloats(name, source.floatsArrays[name]);
  59648. }
  59649. // Color3
  59650. for (name in source.colors3) {
  59651. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59652. }
  59653. // Color3 arrays
  59654. for (name in source.colors3Arrays) {
  59655. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59656. if (i % 3 === 0) {
  59657. arr.push([num]);
  59658. }
  59659. else {
  59660. arr[arr.length - 1].push(num);
  59661. }
  59662. return arr;
  59663. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59664. material.setColor3Array(name, colors);
  59665. }
  59666. // Color4
  59667. for (name in source.colors4) {
  59668. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59669. }
  59670. // Vector2
  59671. for (name in source.vectors2) {
  59672. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59673. }
  59674. // Vector3
  59675. for (name in source.vectors3) {
  59676. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59677. }
  59678. // Vector4
  59679. for (name in source.vectors4) {
  59680. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59681. }
  59682. // Matrix
  59683. for (name in source.matrices) {
  59684. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59685. }
  59686. // Matrix 3x3
  59687. for (name in source.matrices3x3) {
  59688. material.setMatrix3x3(name, source.matrices3x3[name]);
  59689. }
  59690. // Matrix 2x2
  59691. for (name in source.matrices2x2) {
  59692. material.setMatrix2x2(name, source.matrices2x2[name]);
  59693. }
  59694. // Vector2Array
  59695. for (name in source.vectors2Arrays) {
  59696. material.setArray2(name, source.vectors2Arrays[name]);
  59697. }
  59698. // Vector3Array
  59699. for (name in source.vectors3Arrays) {
  59700. material.setArray3(name, source.vectors3Arrays[name]);
  59701. }
  59702. return material;
  59703. };
  59704. return ShaderMaterial;
  59705. }(BABYLON.Material));
  59706. BABYLON.ShaderMaterial = ShaderMaterial;
  59707. })(BABYLON || (BABYLON = {}));
  59708. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59709. var BABYLON;
  59710. (function (BABYLON) {
  59711. var GroundMesh = /** @class */ (function (_super) {
  59712. __extends(GroundMesh, _super);
  59713. function GroundMesh(name, scene) {
  59714. var _this = _super.call(this, name, scene) || this;
  59715. _this.generateOctree = false;
  59716. return _this;
  59717. }
  59718. GroundMesh.prototype.getClassName = function () {
  59719. return "GroundMesh";
  59720. };
  59721. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59722. get: function () {
  59723. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59724. },
  59725. enumerable: true,
  59726. configurable: true
  59727. });
  59728. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59729. get: function () {
  59730. return this._subdivisionsX;
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59736. get: function () {
  59737. return this._subdivisionsY;
  59738. },
  59739. enumerable: true,
  59740. configurable: true
  59741. });
  59742. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59743. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59744. this._subdivisionsX = chunksCount;
  59745. this._subdivisionsY = chunksCount;
  59746. this.subdivide(chunksCount);
  59747. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59748. };
  59749. /**
  59750. * Returns a height (y) value in the Worl system :
  59751. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59752. * Returns the ground y position if (x, z) are outside the ground surface.
  59753. */
  59754. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59755. var world = this.getWorldMatrix();
  59756. var invMat = BABYLON.Tmp.Matrix[5];
  59757. world.invertToRef(invMat);
  59758. var tmpVect = BABYLON.Tmp.Vector3[8];
  59759. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59760. x = tmpVect.x;
  59761. z = tmpVect.z;
  59762. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59763. return this.position.y;
  59764. }
  59765. if (!this._heightQuads || this._heightQuads.length == 0) {
  59766. this._initHeightQuads();
  59767. this._computeHeightQuads();
  59768. }
  59769. var facet = this._getFacetAt(x, z);
  59770. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59771. // return y in the World system
  59772. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59773. return tmpVect.y;
  59774. };
  59775. /**
  59776. * Returns a normalized vector (Vector3) orthogonal to the ground
  59777. * at the ground coordinates (x, z) expressed in the World system.
  59778. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59779. */
  59780. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59781. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59782. this.getNormalAtCoordinatesToRef(x, z, normal);
  59783. return normal;
  59784. };
  59785. /**
  59786. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59787. * at the ground coordinates (x, z) expressed in the World system.
  59788. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59789. * Returns the GroundMesh.
  59790. */
  59791. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59792. var world = this.getWorldMatrix();
  59793. var tmpMat = BABYLON.Tmp.Matrix[5];
  59794. world.invertToRef(tmpMat);
  59795. var tmpVect = BABYLON.Tmp.Vector3[8];
  59796. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59797. x = tmpVect.x;
  59798. z = tmpVect.z;
  59799. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59800. return this;
  59801. }
  59802. if (!this._heightQuads || this._heightQuads.length == 0) {
  59803. this._initHeightQuads();
  59804. this._computeHeightQuads();
  59805. }
  59806. var facet = this._getFacetAt(x, z);
  59807. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59808. return this;
  59809. };
  59810. /**
  59811. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59812. * if the ground has been updated.
  59813. * This can be used in the render loop.
  59814. * Returns the GroundMesh.
  59815. */
  59816. GroundMesh.prototype.updateCoordinateHeights = function () {
  59817. if (!this._heightQuads || this._heightQuads.length == 0) {
  59818. this._initHeightQuads();
  59819. }
  59820. this._computeHeightQuads();
  59821. return this;
  59822. };
  59823. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59824. GroundMesh.prototype._getFacetAt = function (x, z) {
  59825. // retrieve col and row from x, z coordinates in the ground local system
  59826. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59827. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59828. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59829. var facet;
  59830. if (z < quad.slope.x * x + quad.slope.y) {
  59831. facet = quad.facet1;
  59832. }
  59833. else {
  59834. facet = quad.facet2;
  59835. }
  59836. return facet;
  59837. };
  59838. // Creates and populates the heightMap array with "facet" elements :
  59839. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59840. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59841. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59842. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59843. // Returns the GroundMesh.
  59844. GroundMesh.prototype._initHeightQuads = function () {
  59845. var subdivisionsX = this._subdivisionsX;
  59846. var subdivisionsY = this._subdivisionsY;
  59847. this._heightQuads = new Array();
  59848. for (var row = 0; row < subdivisionsY; row++) {
  59849. for (var col = 0; col < subdivisionsX; col++) {
  59850. 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) };
  59851. this._heightQuads[row * subdivisionsX + col] = quad;
  59852. }
  59853. }
  59854. return this;
  59855. };
  59856. // Compute each quad element values and update the the heightMap array :
  59857. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59858. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59859. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59860. // Returns the GroundMesh.
  59861. GroundMesh.prototype._computeHeightQuads = function () {
  59862. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59863. if (!positions) {
  59864. return this;
  59865. }
  59866. var v1 = BABYLON.Tmp.Vector3[3];
  59867. var v2 = BABYLON.Tmp.Vector3[2];
  59868. var v3 = BABYLON.Tmp.Vector3[1];
  59869. var v4 = BABYLON.Tmp.Vector3[0];
  59870. var v1v2 = BABYLON.Tmp.Vector3[4];
  59871. var v1v3 = BABYLON.Tmp.Vector3[5];
  59872. var v1v4 = BABYLON.Tmp.Vector3[6];
  59873. var norm1 = BABYLON.Tmp.Vector3[7];
  59874. var norm2 = BABYLON.Tmp.Vector3[8];
  59875. var i = 0;
  59876. var j = 0;
  59877. var k = 0;
  59878. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59879. var h = 0;
  59880. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59881. var d2 = 0;
  59882. var subdivisionsX = this._subdivisionsX;
  59883. var subdivisionsY = this._subdivisionsY;
  59884. for (var row = 0; row < subdivisionsY; row++) {
  59885. for (var col = 0; col < subdivisionsX; col++) {
  59886. i = col * 3;
  59887. j = row * (subdivisionsX + 1) * 3;
  59888. k = (row + 1) * (subdivisionsX + 1) * 3;
  59889. v1.x = positions[j + i];
  59890. v1.y = positions[j + i + 1];
  59891. v1.z = positions[j + i + 2];
  59892. v2.x = positions[j + i + 3];
  59893. v2.y = positions[j + i + 4];
  59894. v2.z = positions[j + i + 5];
  59895. v3.x = positions[k + i];
  59896. v3.y = positions[k + i + 1];
  59897. v3.z = positions[k + i + 2];
  59898. v4.x = positions[k + i + 3];
  59899. v4.y = positions[k + i + 4];
  59900. v4.z = positions[k + i + 5];
  59901. // 2D slope V1V4
  59902. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59903. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59904. // facet equations :
  59905. // we compute each facet normal vector
  59906. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59907. // we compute the value d by applying the equation to v1 which belongs to the plane
  59908. // then we store the facet equation in a Vector4
  59909. v2.subtractToRef(v1, v1v2);
  59910. v3.subtractToRef(v1, v1v3);
  59911. v4.subtractToRef(v1, v1v4);
  59912. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59913. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59914. norm1.normalize();
  59915. norm2.normalize();
  59916. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59917. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59918. var quad = this._heightQuads[row * subdivisionsX + col];
  59919. quad.slope.copyFromFloats(cd, h);
  59920. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59921. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59922. }
  59923. }
  59924. return this;
  59925. };
  59926. GroundMesh.prototype.serialize = function (serializationObject) {
  59927. _super.prototype.serialize.call(this, serializationObject);
  59928. serializationObject.subdivisionsX = this._subdivisionsX;
  59929. serializationObject.subdivisionsY = this._subdivisionsY;
  59930. serializationObject.minX = this._minX;
  59931. serializationObject.maxX = this._maxX;
  59932. serializationObject.minZ = this._minZ;
  59933. serializationObject.maxZ = this._maxZ;
  59934. serializationObject.width = this._width;
  59935. serializationObject.height = this._height;
  59936. };
  59937. GroundMesh.Parse = function (parsedMesh, scene) {
  59938. var result = new GroundMesh(parsedMesh.name, scene);
  59939. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59940. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59941. result._minX = parsedMesh.minX;
  59942. result._maxX = parsedMesh.maxX;
  59943. result._minZ = parsedMesh.minZ;
  59944. result._maxZ = parsedMesh.maxZ;
  59945. result._width = parsedMesh.width;
  59946. result._height = parsedMesh.height;
  59947. return result;
  59948. };
  59949. return GroundMesh;
  59950. }(BABYLON.Mesh));
  59951. BABYLON.GroundMesh = GroundMesh;
  59952. })(BABYLON || (BABYLON = {}));
  59953. //# sourceMappingURL=babylon.groundMesh.js.map
  59954. var BABYLON;
  59955. (function (BABYLON) {
  59956. /**
  59957. * Creates an instance based on a source mesh.
  59958. */
  59959. var InstancedMesh = /** @class */ (function (_super) {
  59960. __extends(InstancedMesh, _super);
  59961. function InstancedMesh(name, source) {
  59962. var _this = _super.call(this, name, source.getScene()) || this;
  59963. source.instances.push(_this);
  59964. _this._sourceMesh = source;
  59965. _this.position.copyFrom(source.position);
  59966. _this.rotation.copyFrom(source.rotation);
  59967. _this.scaling.copyFrom(source.scaling);
  59968. if (source.rotationQuaternion) {
  59969. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59970. }
  59971. _this.infiniteDistance = source.infiniteDistance;
  59972. _this.setPivotMatrix(source.getPivotMatrix());
  59973. _this.refreshBoundingInfo();
  59974. _this._syncSubMeshes();
  59975. return _this;
  59976. }
  59977. /**
  59978. * Returns the string "InstancedMesh".
  59979. */
  59980. InstancedMesh.prototype.getClassName = function () {
  59981. return "InstancedMesh";
  59982. };
  59983. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59984. // Methods
  59985. get: function () {
  59986. return this._sourceMesh.receiveShadows;
  59987. },
  59988. enumerable: true,
  59989. configurable: true
  59990. });
  59991. Object.defineProperty(InstancedMesh.prototype, "material", {
  59992. get: function () {
  59993. return this._sourceMesh.material;
  59994. },
  59995. enumerable: true,
  59996. configurable: true
  59997. });
  59998. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59999. get: function () {
  60000. return this._sourceMesh.visibility;
  60001. },
  60002. enumerable: true,
  60003. configurable: true
  60004. });
  60005. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60006. get: function () {
  60007. return this._sourceMesh.skeleton;
  60008. },
  60009. enumerable: true,
  60010. configurable: true
  60011. });
  60012. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60013. get: function () {
  60014. return this._sourceMesh.renderingGroupId;
  60015. },
  60016. set: function (value) {
  60017. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60018. return;
  60019. }
  60020. //no-op with warning
  60021. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60022. },
  60023. enumerable: true,
  60024. configurable: true
  60025. });
  60026. /**
  60027. * Returns the total number of vertices (integer).
  60028. */
  60029. InstancedMesh.prototype.getTotalVertices = function () {
  60030. return this._sourceMesh.getTotalVertices();
  60031. };
  60032. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60033. get: function () {
  60034. return this._sourceMesh;
  60035. },
  60036. enumerable: true,
  60037. configurable: true
  60038. });
  60039. /**
  60040. * Is this node ready to be used/rendered
  60041. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60042. * @return {boolean} is it ready
  60043. */
  60044. InstancedMesh.prototype.isReady = function (completeCheck) {
  60045. if (completeCheck === void 0) { completeCheck = false; }
  60046. return this._sourceMesh.isReady(completeCheck, true);
  60047. };
  60048. /**
  60049. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60050. */
  60051. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60052. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60053. };
  60054. /**
  60055. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60056. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60057. * The `data` are either a numeric array either a Float32Array.
  60058. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60059. * 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).
  60060. * Note that a new underlying VertexBuffer object is created each call.
  60061. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60062. *
  60063. * Possible `kind` values :
  60064. * - BABYLON.VertexBuffer.PositionKind
  60065. * - BABYLON.VertexBuffer.UVKind
  60066. * - BABYLON.VertexBuffer.UV2Kind
  60067. * - BABYLON.VertexBuffer.UV3Kind
  60068. * - BABYLON.VertexBuffer.UV4Kind
  60069. * - BABYLON.VertexBuffer.UV5Kind
  60070. * - BABYLON.VertexBuffer.UV6Kind
  60071. * - BABYLON.VertexBuffer.ColorKind
  60072. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60073. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60074. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60075. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60076. *
  60077. * Returns the Mesh.
  60078. */
  60079. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60080. if (this.sourceMesh) {
  60081. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60082. }
  60083. return this.sourceMesh;
  60084. };
  60085. /**
  60086. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60087. * If the mesh has no geometry, it is simply returned as it is.
  60088. * The `data` are either a numeric array either a Float32Array.
  60089. * No new underlying VertexBuffer object is created.
  60090. * 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.
  60091. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60092. *
  60093. * Possible `kind` values :
  60094. * - BABYLON.VertexBuffer.PositionKind
  60095. * - BABYLON.VertexBuffer.UVKind
  60096. * - BABYLON.VertexBuffer.UV2Kind
  60097. * - BABYLON.VertexBuffer.UV3Kind
  60098. * - BABYLON.VertexBuffer.UV4Kind
  60099. * - BABYLON.VertexBuffer.UV5Kind
  60100. * - BABYLON.VertexBuffer.UV6Kind
  60101. * - BABYLON.VertexBuffer.ColorKind
  60102. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60103. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60104. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60105. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60106. *
  60107. * Returns the Mesh.
  60108. */
  60109. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60110. if (this.sourceMesh) {
  60111. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60112. }
  60113. return this.sourceMesh;
  60114. };
  60115. /**
  60116. * Sets the mesh indices.
  60117. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60118. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60119. * This method creates a new index buffer each call.
  60120. * Returns the Mesh.
  60121. */
  60122. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60123. if (totalVertices === void 0) { totalVertices = null; }
  60124. if (this.sourceMesh) {
  60125. this.sourceMesh.setIndices(indices, totalVertices);
  60126. }
  60127. return this.sourceMesh;
  60128. };
  60129. /**
  60130. * Boolean : True if the mesh owns the requested kind of data.
  60131. */
  60132. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60133. return this._sourceMesh.isVerticesDataPresent(kind);
  60134. };
  60135. /**
  60136. * Returns an array of indices (IndicesArray).
  60137. */
  60138. InstancedMesh.prototype.getIndices = function () {
  60139. return this._sourceMesh.getIndices();
  60140. };
  60141. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60142. get: function () {
  60143. return this._sourceMesh._positions;
  60144. },
  60145. enumerable: true,
  60146. configurable: true
  60147. });
  60148. /**
  60149. * Sets a new updated BoundingInfo to the mesh.
  60150. * Returns the mesh.
  60151. */
  60152. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60153. var meshBB = this._sourceMesh.getBoundingInfo();
  60154. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60155. this._updateBoundingInfo();
  60156. return this;
  60157. };
  60158. InstancedMesh.prototype._preActivate = function () {
  60159. if (this._currentLOD) {
  60160. this._currentLOD._preActivate();
  60161. }
  60162. return this;
  60163. };
  60164. InstancedMesh.prototype._activate = function (renderId) {
  60165. if (this._currentLOD) {
  60166. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60167. }
  60168. return this;
  60169. };
  60170. /**
  60171. * Returns the current associated LOD AbstractMesh.
  60172. */
  60173. InstancedMesh.prototype.getLOD = function (camera) {
  60174. if (!camera) {
  60175. return this;
  60176. }
  60177. var boundingInfo = this.getBoundingInfo();
  60178. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60179. if (this._currentLOD === this.sourceMesh) {
  60180. return this;
  60181. }
  60182. return this._currentLOD;
  60183. };
  60184. InstancedMesh.prototype._syncSubMeshes = function () {
  60185. this.releaseSubMeshes();
  60186. if (this._sourceMesh.subMeshes) {
  60187. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60188. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60189. }
  60190. }
  60191. return this;
  60192. };
  60193. InstancedMesh.prototype._generatePointsArray = function () {
  60194. return this._sourceMesh._generatePointsArray();
  60195. };
  60196. /**
  60197. * Creates a new InstancedMesh from the current mesh.
  60198. * - name (string) : the cloned mesh name
  60199. * - newParent (optional Node) : the optional Node to parent the clone to.
  60200. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60201. *
  60202. * Returns the clone.
  60203. */
  60204. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60205. var result = this._sourceMesh.createInstance(name);
  60206. // Deep copy
  60207. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60208. // Bounding info
  60209. this.refreshBoundingInfo();
  60210. // Parent
  60211. if (newParent) {
  60212. result.parent = newParent;
  60213. }
  60214. if (!doNotCloneChildren) {
  60215. // Children
  60216. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60217. var mesh = this.getScene().meshes[index];
  60218. if (mesh.parent === this) {
  60219. mesh.clone(mesh.name, result);
  60220. }
  60221. }
  60222. }
  60223. result.computeWorldMatrix(true);
  60224. return result;
  60225. };
  60226. /**
  60227. * Disposes the InstancedMesh.
  60228. * Returns nothing.
  60229. */
  60230. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60231. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60232. // Remove from mesh
  60233. var index = this._sourceMesh.instances.indexOf(this);
  60234. this._sourceMesh.instances.splice(index, 1);
  60235. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60236. };
  60237. return InstancedMesh;
  60238. }(BABYLON.AbstractMesh));
  60239. BABYLON.InstancedMesh = InstancedMesh;
  60240. })(BABYLON || (BABYLON = {}));
  60241. //# sourceMappingURL=babylon.instancedMesh.js.map
  60242. var BABYLON;
  60243. (function (BABYLON) {
  60244. var LinesMesh = /** @class */ (function (_super) {
  60245. __extends(LinesMesh, _super);
  60246. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60247. if (scene === void 0) { scene = null; }
  60248. if (parent === void 0) { parent = null; }
  60249. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60250. _this.useVertexColor = useVertexColor;
  60251. _this.useVertexAlpha = useVertexAlpha;
  60252. _this.color = new BABYLON.Color3(1, 1, 1);
  60253. _this.alpha = 1;
  60254. if (source) {
  60255. _this.color = source.color.clone();
  60256. _this.alpha = source.alpha;
  60257. _this.useVertexColor = source.useVertexColor;
  60258. _this.useVertexAlpha = source.useVertexAlpha;
  60259. }
  60260. _this._intersectionThreshold = 0.1;
  60261. var defines = [];
  60262. var options = {
  60263. attributes: [BABYLON.VertexBuffer.PositionKind],
  60264. uniforms: ["world", "viewProjection"],
  60265. needAlphaBlending: true,
  60266. defines: defines
  60267. };
  60268. if (useVertexAlpha === false) {
  60269. options.needAlphaBlending = false;
  60270. }
  60271. if (!useVertexColor) {
  60272. options.uniforms.push("color");
  60273. }
  60274. else {
  60275. options.defines.push("#define VERTEXCOLOR");
  60276. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60277. }
  60278. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60279. return _this;
  60280. }
  60281. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60282. /**
  60283. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60284. * This margin is expressed in world space coordinates, so its value may vary.
  60285. * Default value is 0.1
  60286. * @returns the intersection Threshold value.
  60287. */
  60288. get: function () {
  60289. return this._intersectionThreshold;
  60290. },
  60291. /**
  60292. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60293. * This margin is expressed in world space coordinates, so its value may vary.
  60294. * @param value the new threshold to apply
  60295. */
  60296. set: function (value) {
  60297. if (this._intersectionThreshold === value) {
  60298. return;
  60299. }
  60300. this._intersectionThreshold = value;
  60301. if (this.geometry) {
  60302. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60303. }
  60304. },
  60305. enumerable: true,
  60306. configurable: true
  60307. });
  60308. /**
  60309. * Returns the string "LineMesh"
  60310. */
  60311. LinesMesh.prototype.getClassName = function () {
  60312. return "LinesMesh";
  60313. };
  60314. Object.defineProperty(LinesMesh.prototype, "material", {
  60315. get: function () {
  60316. return this._colorShader;
  60317. },
  60318. set: function (value) {
  60319. // Do nothing
  60320. },
  60321. enumerable: true,
  60322. configurable: true
  60323. });
  60324. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60325. get: function () {
  60326. return false;
  60327. },
  60328. enumerable: true,
  60329. configurable: true
  60330. });
  60331. LinesMesh.prototype.createInstance = function (name) {
  60332. throw new Error("LinesMeshes do not support createInstance.");
  60333. };
  60334. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60335. if (!this._geometry) {
  60336. return this;
  60337. }
  60338. // VBOs
  60339. this._geometry._bind(this._colorShader.getEffect());
  60340. // Color
  60341. if (!this.useVertexColor) {
  60342. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60343. }
  60344. return this;
  60345. };
  60346. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60347. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60348. return this;
  60349. }
  60350. var engine = this.getScene().getEngine();
  60351. // Draw order
  60352. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60353. return this;
  60354. };
  60355. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60356. this._colorShader.dispose();
  60357. _super.prototype.dispose.call(this, doNotRecurse);
  60358. };
  60359. /**
  60360. * Returns a new LineMesh object cloned from the current one.
  60361. */
  60362. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60363. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60364. };
  60365. return LinesMesh;
  60366. }(BABYLON.Mesh));
  60367. BABYLON.LinesMesh = LinesMesh;
  60368. })(BABYLON || (BABYLON = {}));
  60369. //# sourceMappingURL=babylon.linesMesh.js.map
  60370. var BABYLON;
  60371. (function (BABYLON) {
  60372. /**
  60373. * Class containing static functions to help procedurally build meshes
  60374. */
  60375. var MeshBuilder = /** @class */ (function () {
  60376. function MeshBuilder() {
  60377. }
  60378. MeshBuilder.updateSideOrientation = function (orientation) {
  60379. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60380. return BABYLON.Mesh.DOUBLESIDE;
  60381. }
  60382. if (orientation === undefined || orientation === null) {
  60383. return BABYLON.Mesh.FRONTSIDE;
  60384. }
  60385. return orientation;
  60386. };
  60387. /**
  60388. * Creates a box mesh
  60389. * * The parameter `size` sets the size (float) of each box side (default 1)
  60390. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60391. * * 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)
  60392. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60393. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60394. * * 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
  60395. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60396. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60397. * @param name defines the name of the mesh
  60398. * @param options defines the options used to create the mesh
  60399. * @param scene defines the hosting scene
  60400. * @returns the box mesh
  60401. */
  60402. MeshBuilder.CreateBox = function (name, options, scene) {
  60403. if (scene === void 0) { scene = null; }
  60404. var box = new BABYLON.Mesh(name, scene);
  60405. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60406. box._originalBuilderSideOrientation = options.sideOrientation;
  60407. var vertexData = BABYLON.VertexData.CreateBox(options);
  60408. vertexData.applyToMesh(box, options.updatable);
  60409. return box;
  60410. };
  60411. /**
  60412. * Creates a sphere mesh
  60413. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60414. * * 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`)
  60415. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60416. * * 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
  60417. * * 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)
  60418. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60419. * * 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
  60420. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60421. * @param name defines the name of the mesh
  60422. * @param options defines the options used to create the mesh
  60423. * @param scene defines the hosting scene
  60424. * @returns the sphere mesh
  60425. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60426. */
  60427. MeshBuilder.CreateSphere = function (name, options, scene) {
  60428. var sphere = new BABYLON.Mesh(name, scene);
  60429. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60430. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60431. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60432. vertexData.applyToMesh(sphere, options.updatable);
  60433. return sphere;
  60434. };
  60435. /**
  60436. * Creates a plane polygonal mesh. By default, this is a disc
  60437. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60438. * * 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
  60439. * * 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
  60440. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60441. * * 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
  60442. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60443. * @param name defines the name of the mesh
  60444. * @param options defines the options used to create the mesh
  60445. * @param scene defines the hosting scene
  60446. * @returns the plane polygonal mesh
  60447. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60448. */
  60449. MeshBuilder.CreateDisc = function (name, options, scene) {
  60450. if (scene === void 0) { scene = null; }
  60451. var disc = new BABYLON.Mesh(name, scene);
  60452. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60453. disc._originalBuilderSideOrientation = options.sideOrientation;
  60454. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60455. vertexData.applyToMesh(disc, options.updatable);
  60456. return disc;
  60457. };
  60458. /**
  60459. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60460. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60461. * * 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`)
  60462. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60463. * * 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
  60464. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60465. * * 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
  60466. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60467. * @param name defines the name of the mesh
  60468. * @param options defines the options used to create the mesh
  60469. * @param scene defines the hosting scene
  60470. * @returns the icosahedron mesh
  60471. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60472. */
  60473. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60474. var sphere = new BABYLON.Mesh(name, scene);
  60475. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60476. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60477. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60478. vertexData.applyToMesh(sphere, options.updatable);
  60479. return sphere;
  60480. };
  60481. ;
  60482. /**
  60483. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60484. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60485. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60486. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60487. * * 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
  60488. * * 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
  60489. * * 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
  60490. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60491. * * 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
  60492. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60493. * * 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
  60494. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60495. * * 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
  60496. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60498. * @param name defines the name of the mesh
  60499. * @param options defines the options used to create the mesh
  60500. * @param scene defines the hosting scene
  60501. * @returns the ribbon mesh
  60502. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60503. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60504. */
  60505. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60506. if (scene === void 0) { scene = null; }
  60507. var pathArray = options.pathArray;
  60508. var closeArray = options.closeArray;
  60509. var closePath = options.closePath;
  60510. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60511. var instance = options.instance;
  60512. var updatable = options.updatable;
  60513. if (instance) { // existing ribbon instance update
  60514. // positionFunction : ribbon case
  60515. // only pathArray and sideOrientation parameters are taken into account for positions update
  60516. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60517. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60518. var positionFunction = function (positions) {
  60519. var minlg = pathArray[0].length;
  60520. var i = 0;
  60521. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60522. for (var si = 1; si <= ns; si++) {
  60523. for (var p = 0; p < pathArray.length; p++) {
  60524. var path = pathArray[p];
  60525. var l = path.length;
  60526. minlg = (minlg < l) ? minlg : l;
  60527. var j = 0;
  60528. while (j < minlg) {
  60529. positions[i] = path[j].x;
  60530. positions[i + 1] = path[j].y;
  60531. positions[i + 2] = path[j].z;
  60532. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60533. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60534. }
  60535. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60536. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60537. }
  60538. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60539. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60540. }
  60541. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60542. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60543. }
  60544. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60545. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60546. }
  60547. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60548. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60549. }
  60550. j++;
  60551. i += 3;
  60552. }
  60553. if (instance._closePath) {
  60554. positions[i] = path[0].x;
  60555. positions[i + 1] = path[0].y;
  60556. positions[i + 2] = path[0].z;
  60557. i += 3;
  60558. }
  60559. }
  60560. }
  60561. };
  60562. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60563. positionFunction(positions);
  60564. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60565. instance._boundingInfo.update(instance._worldMatrix);
  60566. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60567. if (options.colors) {
  60568. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60569. for (var c = 0; c < options.colors.length; c++) {
  60570. colors[c * 4] = options.colors[c].r;
  60571. colors[c * 4 + 1] = options.colors[c].g;
  60572. colors[c * 4 + 2] = options.colors[c].b;
  60573. colors[c * 4 + 3] = options.colors[c].a;
  60574. }
  60575. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60576. }
  60577. if (options.uvs) {
  60578. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60579. for (var i = 0; i < options.uvs.length; i++) {
  60580. uvs[i * 2] = options.uvs[i].x;
  60581. uvs[i * 2 + 1] = options.uvs[i].y;
  60582. }
  60583. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60584. }
  60585. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60586. var indices = instance.getIndices();
  60587. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60588. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60589. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60590. if (instance._closePath) {
  60591. var indexFirst = 0;
  60592. var indexLast = 0;
  60593. for (var p = 0; p < pathArray.length; p++) {
  60594. indexFirst = instance._idx[p] * 3;
  60595. if (p + 1 < pathArray.length) {
  60596. indexLast = (instance._idx[p + 1] - 1) * 3;
  60597. }
  60598. else {
  60599. indexLast = normals.length - 3;
  60600. }
  60601. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60602. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60603. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60604. normals[indexLast] = normals[indexFirst];
  60605. normals[indexLast + 1] = normals[indexFirst + 1];
  60606. normals[indexLast + 2] = normals[indexFirst + 2];
  60607. }
  60608. }
  60609. if (!(instance.areNormalsFrozen)) {
  60610. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60611. }
  60612. }
  60613. return instance;
  60614. }
  60615. else { // new ribbon creation
  60616. var ribbon = new BABYLON.Mesh(name, scene);
  60617. ribbon._originalBuilderSideOrientation = sideOrientation;
  60618. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60619. if (closePath) {
  60620. ribbon._idx = vertexData._idx;
  60621. }
  60622. ribbon._closePath = closePath;
  60623. ribbon._closeArray = closeArray;
  60624. vertexData.applyToMesh(ribbon, updatable);
  60625. return ribbon;
  60626. }
  60627. };
  60628. /**
  60629. * Creates a cylinder or a cone mesh
  60630. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60631. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60632. * * 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.
  60633. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60634. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60635. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60636. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60637. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60638. * * 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).
  60639. * * 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
  60640. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60641. * * 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
  60642. * * 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.
  60643. * * If `enclose` is false, a ring surface is one element.
  60644. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60645. * * 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
  60646. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60647. * * 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
  60648. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60649. * @param name defines the name of the mesh
  60650. * @param options defines the options used to create the mesh
  60651. * @param scene defines the hosting scene
  60652. * @returns the cylinder mesh
  60653. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60654. */
  60655. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60656. var cylinder = new BABYLON.Mesh(name, scene);
  60657. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60658. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60659. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60660. vertexData.applyToMesh(cylinder, options.updatable);
  60661. return cylinder;
  60662. };
  60663. /**
  60664. * Creates a torus mesh
  60665. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60666. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60667. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60668. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60669. * * 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
  60670. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60671. * @param name defines the name of the mesh
  60672. * @param options defines the options used to create the mesh
  60673. * @param scene defines the hosting scene
  60674. * @returns the torus mesh
  60675. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60676. */
  60677. MeshBuilder.CreateTorus = function (name, options, scene) {
  60678. var torus = new BABYLON.Mesh(name, scene);
  60679. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60680. torus._originalBuilderSideOrientation = options.sideOrientation;
  60681. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60682. vertexData.applyToMesh(torus, options.updatable);
  60683. return torus;
  60684. };
  60685. /**
  60686. * Creates a torus knot mesh
  60687. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60688. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60689. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60690. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60692. * * 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
  60693. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60694. * @param name defines the name of the mesh
  60695. * @param options defines the options used to create the mesh
  60696. * @param scene defines the hosting scene
  60697. * @returns the torus knot mesh
  60698. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60699. */
  60700. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60701. var torusKnot = new BABYLON.Mesh(name, scene);
  60702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60703. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60704. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60705. vertexData.applyToMesh(torusKnot, options.updatable);
  60706. return torusKnot;
  60707. };
  60708. /**
  60709. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60710. * * 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
  60711. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60712. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60713. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60714. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60715. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60716. * * 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
  60717. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60719. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60720. * @param name defines the name of the new line system
  60721. * @param options defines the options used to create the line system
  60722. * @param scene defines the hosting scene
  60723. * @returns a new line system mesh
  60724. */
  60725. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60726. var instance = options.instance;
  60727. var lines = options.lines;
  60728. var colors = options.colors;
  60729. if (instance) { // lines update
  60730. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60731. var vertexColor;
  60732. var lineColors;
  60733. if (colors) {
  60734. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60735. }
  60736. var i = 0;
  60737. var c = 0;
  60738. for (var l = 0; l < lines.length; l++) {
  60739. var points = lines[l];
  60740. for (var p = 0; p < points.length; p++) {
  60741. positions[i] = points[p].x;
  60742. positions[i + 1] = points[p].y;
  60743. positions[i + 2] = points[p].z;
  60744. if (colors && vertexColor) {
  60745. lineColors = colors[l];
  60746. vertexColor[c] = lineColors[p].r;
  60747. vertexColor[c + 1] = lineColors[p].g;
  60748. vertexColor[c + 2] = lineColors[p].b;
  60749. vertexColor[c + 3] = lineColors[p].a;
  60750. c += 4;
  60751. }
  60752. i += 3;
  60753. }
  60754. }
  60755. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60756. if (colors && vertexColor) {
  60757. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60758. }
  60759. return instance;
  60760. }
  60761. // line system creation
  60762. var useVertexColor = (colors) ? true : false;
  60763. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60764. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60765. vertexData.applyToMesh(lineSystem, options.updatable);
  60766. return lineSystem;
  60767. };
  60768. /**
  60769. * Creates a line mesh
  60770. * 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
  60771. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60772. * * The parameter `points` is an array successive Vector3
  60773. * * 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
  60774. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60775. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60776. * * When updating an instance, remember that only point positions can change, not the number of points
  60777. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60778. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60779. * @param name defines the name of the new line system
  60780. * @param options defines the options used to create the line system
  60781. * @param scene defines the hosting scene
  60782. * @returns a new line mesh
  60783. */
  60784. MeshBuilder.CreateLines = function (name, options, scene) {
  60785. if (scene === void 0) { scene = null; }
  60786. var colors = (options.colors) ? [options.colors] : null;
  60787. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60788. return lines;
  60789. };
  60790. /**
  60791. * Creates a dashed line mesh
  60792. * * 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
  60793. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60794. * * The parameter `points` is an array successive Vector3
  60795. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60796. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60797. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60798. * * 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
  60799. * * When updating an instance, remember that only point positions can change, not the number of points
  60800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60801. * @param name defines the name of the mesh
  60802. * @param options defines the options used to create the mesh
  60803. * @param scene defines the hosting scene
  60804. * @returns the dashed line mesh
  60805. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60806. */
  60807. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60808. if (scene === void 0) { scene = null; }
  60809. var points = options.points;
  60810. var instance = options.instance;
  60811. var gapSize = options.gapSize || 1;
  60812. var dashSize = options.dashSize || 3;
  60813. if (instance) { // dashed lines update
  60814. var positionFunction = function (positions) {
  60815. var curvect = BABYLON.Vector3.Zero();
  60816. var nbSeg = positions.length / 6;
  60817. var lg = 0;
  60818. var nb = 0;
  60819. var shft = 0;
  60820. var dashshft = 0;
  60821. var curshft = 0;
  60822. var p = 0;
  60823. var i = 0;
  60824. var j = 0;
  60825. for (i = 0; i < points.length - 1; i++) {
  60826. points[i + 1].subtractToRef(points[i], curvect);
  60827. lg += curvect.length();
  60828. }
  60829. shft = lg / nbSeg;
  60830. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60831. for (i = 0; i < points.length - 1; i++) {
  60832. points[i + 1].subtractToRef(points[i], curvect);
  60833. nb = Math.floor(curvect.length() / shft);
  60834. curvect.normalize();
  60835. j = 0;
  60836. while (j < nb && p < positions.length) {
  60837. curshft = shft * j;
  60838. positions[p] = points[i].x + curshft * curvect.x;
  60839. positions[p + 1] = points[i].y + curshft * curvect.y;
  60840. positions[p + 2] = points[i].z + curshft * curvect.z;
  60841. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60842. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60843. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60844. p += 6;
  60845. j++;
  60846. }
  60847. }
  60848. while (p < positions.length) {
  60849. positions[p] = points[i].x;
  60850. positions[p + 1] = points[i].y;
  60851. positions[p + 2] = points[i].z;
  60852. p += 3;
  60853. }
  60854. };
  60855. instance.updateMeshPositions(positionFunction, false);
  60856. return instance;
  60857. }
  60858. // dashed lines creation
  60859. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60860. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60861. vertexData.applyToMesh(dashedLines, options.updatable);
  60862. dashedLines.dashSize = dashSize;
  60863. dashedLines.gapSize = gapSize;
  60864. return dashedLines;
  60865. };
  60866. /**
  60867. * 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.
  60868. * * 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.
  60869. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60870. * * 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.
  60871. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60872. * * 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
  60873. * * 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
  60874. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60875. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60876. * * 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
  60877. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60878. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60879. * @param name defines the name of the mesh
  60880. * @param options defines the options used to create the mesh
  60881. * @param scene defines the hosting scene
  60882. * @returns the extruded shape mesh
  60883. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60884. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60885. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60886. */
  60887. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60888. if (scene === void 0) { scene = null; }
  60889. var path = options.path;
  60890. var shape = options.shape;
  60891. var scale = options.scale || 1;
  60892. var rotation = options.rotation || 0;
  60893. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60894. var updatable = options.updatable;
  60895. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60896. var instance = options.instance || null;
  60897. var invertUV = options.invertUV || false;
  60898. 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);
  60899. };
  60900. /**
  60901. * Creates an custom extruded shape mesh.
  60902. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60903. * * 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.
  60904. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60905. * * 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
  60906. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60907. * * 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
  60908. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60909. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60910. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60911. * * 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
  60912. * * 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
  60913. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60914. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60915. * * 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
  60916. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60917. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60918. * @param name defines the name of the mesh
  60919. * @param options defines the options used to create the mesh
  60920. * @param scene defines the hosting scene
  60921. * @returns the custom extruded shape mesh
  60922. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60923. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60924. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60925. */
  60926. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60927. var path = options.path;
  60928. var shape = options.shape;
  60929. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60930. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60931. var ribbonCloseArray = options.ribbonCloseArray || false;
  60932. var ribbonClosePath = options.ribbonClosePath || false;
  60933. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60934. var updatable = options.updatable;
  60935. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60936. var instance = options.instance;
  60937. var invertUV = options.invertUV || false;
  60938. 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);
  60939. };
  60940. /**
  60941. * Creates lathe mesh.
  60942. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60943. * * 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
  60944. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60945. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60946. * * 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
  60947. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60948. * * 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
  60949. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60950. * * 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
  60951. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60953. * @param name defines the name of the mesh
  60954. * @param options defines the options used to create the mesh
  60955. * @param scene defines the hosting scene
  60956. * @returns the lathe mesh
  60957. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60958. */
  60959. MeshBuilder.CreateLathe = function (name, options, scene) {
  60960. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60961. var closed = (options.closed === undefined) ? true : options.closed;
  60962. var shape = options.shape;
  60963. var radius = options.radius || 1;
  60964. var tessellation = options.tessellation || 64;
  60965. var updatable = options.updatable;
  60966. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60967. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60968. var pi2 = Math.PI * 2;
  60969. var paths = new Array();
  60970. var invertUV = options.invertUV || false;
  60971. var i = 0;
  60972. var p = 0;
  60973. var step = pi2 / tessellation * arc;
  60974. var rotated;
  60975. var path = new Array();
  60976. for (i = 0; i <= tessellation; i++) {
  60977. var path = [];
  60978. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60979. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60980. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60981. }
  60982. for (p = 0; p < shape.length; p++) {
  60983. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60984. path.push(rotated);
  60985. }
  60986. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60987. 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));
  60988. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60989. }
  60990. paths.push(path);
  60991. }
  60992. // lathe ribbon
  60993. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60994. return lathe;
  60995. };
  60996. /**
  60997. * Creates a plane mesh
  60998. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60999. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61000. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61002. * * 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
  61003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61004. * @param name defines the name of the mesh
  61005. * @param options defines the options used to create the mesh
  61006. * @param scene defines the hosting scene
  61007. * @returns the plane mesh
  61008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61009. */
  61010. MeshBuilder.CreatePlane = function (name, options, scene) {
  61011. var plane = new BABYLON.Mesh(name, scene);
  61012. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61013. plane._originalBuilderSideOrientation = options.sideOrientation;
  61014. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61015. vertexData.applyToMesh(plane, options.updatable);
  61016. if (options.sourcePlane) {
  61017. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61018. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61019. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61020. plane.rotate(vectorProduct, product);
  61021. }
  61022. return plane;
  61023. };
  61024. /**
  61025. * Creates a ground mesh
  61026. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61027. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61028. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61029. * @param name defines the name of the mesh
  61030. * @param options defines the options used to create the mesh
  61031. * @param scene defines the hosting scene
  61032. * @returns the ground mesh
  61033. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61034. */
  61035. MeshBuilder.CreateGround = function (name, options, scene) {
  61036. var ground = new BABYLON.GroundMesh(name, scene);
  61037. ground._setReady(false);
  61038. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61039. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61040. ground._width = options.width || 1;
  61041. ground._height = options.height || 1;
  61042. ground._maxX = ground._width / 2;
  61043. ground._maxZ = ground._height / 2;
  61044. ground._minX = -ground._maxX;
  61045. ground._minZ = -ground._maxZ;
  61046. var vertexData = BABYLON.VertexData.CreateGround(options);
  61047. vertexData.applyToMesh(ground, options.updatable);
  61048. ground._setReady(true);
  61049. return ground;
  61050. };
  61051. /**
  61052. * Creates a tiled ground mesh
  61053. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61054. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61055. * * 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
  61056. * * 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
  61057. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61058. * @param name defines the name of the mesh
  61059. * @param options defines the options used to create the mesh
  61060. * @param scene defines the hosting scene
  61061. * @returns the tiled ground mesh
  61062. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61063. */
  61064. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61065. var tiledGround = new BABYLON.Mesh(name, scene);
  61066. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61067. vertexData.applyToMesh(tiledGround, options.updatable);
  61068. return tiledGround;
  61069. };
  61070. /**
  61071. * Creates a ground mesh from a height map
  61072. * * The parameter `url` sets the URL of the height map image resource.
  61073. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61074. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61075. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61076. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61077. * * 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.
  61078. * * 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).
  61079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61080. * @param name defines the name of the mesh
  61081. * @param url defines the url to the height map
  61082. * @param options defines the options used to create the mesh
  61083. * @param scene defines the hosting scene
  61084. * @returns the ground mesh
  61085. * @see http://doc.babylonjs.com/babylon101/height_map
  61086. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61087. */
  61088. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61089. var width = options.width || 10.0;
  61090. var height = options.height || 10.0;
  61091. var subdivisions = options.subdivisions || 1 | 0;
  61092. var minHeight = options.minHeight || 0.0;
  61093. var maxHeight = options.maxHeight || 1.0;
  61094. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61095. var updatable = options.updatable;
  61096. var onReady = options.onReady;
  61097. var ground = new BABYLON.GroundMesh(name, scene);
  61098. ground._subdivisionsX = subdivisions;
  61099. ground._subdivisionsY = subdivisions;
  61100. ground._width = width;
  61101. ground._height = height;
  61102. ground._maxX = ground._width / 2.0;
  61103. ground._maxZ = ground._height / 2.0;
  61104. ground._minX = -ground._maxX;
  61105. ground._minZ = -ground._maxZ;
  61106. ground._setReady(false);
  61107. var onload = function (img) {
  61108. // Getting height map data
  61109. var canvas = document.createElement("canvas");
  61110. var context = canvas.getContext("2d");
  61111. if (!context) {
  61112. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61113. }
  61114. if (scene.isDisposed) {
  61115. return;
  61116. }
  61117. var bufferWidth = img.width;
  61118. var bufferHeight = img.height;
  61119. canvas.width = bufferWidth;
  61120. canvas.height = bufferHeight;
  61121. context.drawImage(img, 0, 0);
  61122. // Create VertexData from map data
  61123. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61124. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61125. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61126. width: width, height: height,
  61127. subdivisions: subdivisions,
  61128. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61129. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61130. });
  61131. vertexData.applyToMesh(ground, updatable);
  61132. //execute ready callback, if set
  61133. if (onReady) {
  61134. onReady(ground);
  61135. }
  61136. ground._setReady(true);
  61137. };
  61138. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61139. return ground;
  61140. };
  61141. /**
  61142. * Creates a polygon mesh
  61143. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61144. * * 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
  61145. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61146. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61147. * * 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)
  61148. * * Remember you can only change the shape positions, not their number when updating a polygon
  61149. * @param name defines the name of the mesh
  61150. * @param options defines the options used to create the mesh
  61151. * @param scene defines the hosting scene
  61152. * @returns the polygon mesh
  61153. */
  61154. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61155. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61156. var shape = options.shape;
  61157. var holes = options.holes || [];
  61158. var depth = options.depth || 0;
  61159. var contours = [];
  61160. var hole = [];
  61161. for (var i = 0; i < shape.length; i++) {
  61162. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61163. }
  61164. var epsilon = 0.00000001;
  61165. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61166. contours.pop();
  61167. }
  61168. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61169. for (var hNb = 0; hNb < holes.length; hNb++) {
  61170. hole = [];
  61171. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61172. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61173. }
  61174. polygonTriangulation.addHole(hole);
  61175. }
  61176. var polygon = polygonTriangulation.build(options.updatable, depth);
  61177. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61178. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61179. vertexData.applyToMesh(polygon, options.updatable);
  61180. return polygon;
  61181. };
  61182. ;
  61183. /**
  61184. * Creates an extruded polygon mesh, with depth in the Y direction.
  61185. * * 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)
  61186. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61187. * @param name defines the name of the mesh
  61188. * @param options defines the options used to create the mesh
  61189. * @param scene defines the hosting scene
  61190. * @returns the polygon mesh
  61191. */
  61192. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61193. return MeshBuilder.CreatePolygon(name, options, scene);
  61194. };
  61195. ;
  61196. /**
  61197. * Creates a tube mesh.
  61198. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61199. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61200. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61201. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61202. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61203. * * 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)
  61204. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61205. * * 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
  61206. * * 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
  61207. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61208. * * 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
  61209. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61211. * @param name defines the name of the mesh
  61212. * @param options defines the options used to create the mesh
  61213. * @param scene defines the hosting scene
  61214. * @returns the tube mesh
  61215. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61216. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61217. */
  61218. MeshBuilder.CreateTube = function (name, options, scene) {
  61219. var path = options.path;
  61220. var instance = options.instance;
  61221. var radius = 1.0;
  61222. if (instance) {
  61223. radius = instance.radius;
  61224. }
  61225. if (options.radius !== undefined) {
  61226. radius = options.radius;
  61227. }
  61228. ;
  61229. var tessellation = options.tessellation || 64 | 0;
  61230. var radiusFunction = options.radiusFunction || null;
  61231. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61232. var invertUV = options.invertUV || false;
  61233. var updatable = options.updatable;
  61234. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61235. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61236. // tube geometry
  61237. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61238. var tangents = path3D.getTangents();
  61239. var normals = path3D.getNormals();
  61240. var distances = path3D.getDistances();
  61241. var pi2 = Math.PI * 2;
  61242. var step = pi2 / tessellation * arc;
  61243. var returnRadius = function () { return radius; };
  61244. var radiusFunctionFinal = radiusFunction || returnRadius;
  61245. var circlePath;
  61246. var rad;
  61247. var normal;
  61248. var rotated;
  61249. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61250. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61251. for (var i = 0; i < path.length; i++) {
  61252. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61253. circlePath = Array(); // current circle array
  61254. normal = normals[i]; // current normal
  61255. for (var t = 0; t < tessellation; t++) {
  61256. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61257. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61258. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61259. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61260. circlePath[t] = rotated;
  61261. }
  61262. circlePaths[index] = circlePath;
  61263. index++;
  61264. }
  61265. // cap
  61266. var capPath = function (nbPoints, pathIndex) {
  61267. var pointCap = Array();
  61268. for (var i = 0; i < nbPoints; i++) {
  61269. pointCap.push(path[pathIndex]);
  61270. }
  61271. return pointCap;
  61272. };
  61273. switch (cap) {
  61274. case BABYLON.Mesh.NO_CAP:
  61275. break;
  61276. case BABYLON.Mesh.CAP_START:
  61277. circlePaths[0] = capPath(tessellation, 0);
  61278. circlePaths[1] = circlePaths[2].slice(0);
  61279. break;
  61280. case BABYLON.Mesh.CAP_END:
  61281. circlePaths[index] = circlePaths[index - 1].slice(0);
  61282. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61283. break;
  61284. case BABYLON.Mesh.CAP_ALL:
  61285. circlePaths[0] = capPath(tessellation, 0);
  61286. circlePaths[1] = circlePaths[2].slice(0);
  61287. circlePaths[index] = circlePaths[index - 1].slice(0);
  61288. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61289. break;
  61290. default:
  61291. break;
  61292. }
  61293. return circlePaths;
  61294. };
  61295. var path3D;
  61296. var pathArray;
  61297. if (instance) { // tube update
  61298. var arc = options.arc || instance.arc;
  61299. path3D = (instance.path3D).update(path);
  61300. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61301. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61302. instance.path3D = path3D;
  61303. instance.pathArray = pathArray;
  61304. instance.arc = arc;
  61305. instance.radius = radius;
  61306. return instance;
  61307. }
  61308. // tube creation
  61309. path3D = new BABYLON.Path3D(path);
  61310. var newPathArray = new Array();
  61311. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61312. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61313. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61314. tube.pathArray = pathArray;
  61315. tube.path3D = path3D;
  61316. tube.tessellation = tessellation;
  61317. tube.cap = cap;
  61318. tube.arc = options.arc;
  61319. tube.radius = radius;
  61320. return tube;
  61321. };
  61322. /**
  61323. * Creates a polyhedron mesh
  61324. * * 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
  61325. * * The parameter `size` (positive float, default 1) sets the polygon size
  61326. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61327. * * 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`
  61328. * * 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
  61329. * * 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)`)
  61330. * * 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
  61331. * * 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
  61332. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61333. * * 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
  61334. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61335. * @param name defines the name of the mesh
  61336. * @param options defines the options used to create the mesh
  61337. * @param scene defines the hosting scene
  61338. * @returns the polyhedron mesh
  61339. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61340. */
  61341. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61342. var polyhedron = new BABYLON.Mesh(name, scene);
  61343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61344. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61345. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61346. vertexData.applyToMesh(polyhedron, options.updatable);
  61347. return polyhedron;
  61348. };
  61349. /**
  61350. * Creates a decal mesh.
  61351. * 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
  61352. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61353. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61354. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61355. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61356. * @param name defines the name of the mesh
  61357. * @param sourceMesh defines the mesh where the decal must be applied
  61358. * @param options defines the options used to create the mesh
  61359. * @param scene defines the hosting scene
  61360. * @returns the decal mesh
  61361. * @see http://doc.babylonjs.com/how_to/decals
  61362. */
  61363. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61364. var indices = sourceMesh.getIndices();
  61365. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61366. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61367. var position = options.position || BABYLON.Vector3.Zero();
  61368. var normal = options.normal || BABYLON.Vector3.Up();
  61369. var size = options.size || BABYLON.Vector3.One();
  61370. var angle = options.angle || 0;
  61371. // Getting correct rotation
  61372. if (!normal) {
  61373. var target = new BABYLON.Vector3(0, 0, 1);
  61374. var camera = sourceMesh.getScene().activeCamera;
  61375. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61376. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61377. }
  61378. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61379. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61380. var pitch = Math.atan2(normal.y, len);
  61381. // Matrix
  61382. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61383. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61384. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61385. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61386. var vertexData = new BABYLON.VertexData();
  61387. vertexData.indices = [];
  61388. vertexData.positions = [];
  61389. vertexData.normals = [];
  61390. vertexData.uvs = [];
  61391. var currentVertexDataIndex = 0;
  61392. var extractDecalVector3 = function (indexId) {
  61393. var result = new BABYLON.PositionNormalVertex();
  61394. if (!indices || !positions || !normals) {
  61395. return result;
  61396. }
  61397. var vertexId = indices[indexId];
  61398. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61399. // Send vector to decal local world
  61400. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61401. // Get normal
  61402. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61403. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61404. return result;
  61405. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61406. var clip = function (vertices, axis) {
  61407. if (vertices.length === 0) {
  61408. return vertices;
  61409. }
  61410. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61411. var clipVertices = function (v0, v1) {
  61412. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61413. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61414. };
  61415. var result = new Array();
  61416. for (var index = 0; index < vertices.length; index += 3) {
  61417. var v1Out;
  61418. var v2Out;
  61419. var v3Out;
  61420. var total = 0;
  61421. var nV1 = null;
  61422. var nV2 = null;
  61423. var nV3 = null;
  61424. var nV4 = null;
  61425. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61426. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61427. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61428. v1Out = d1 > 0;
  61429. v2Out = d2 > 0;
  61430. v3Out = d3 > 0;
  61431. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61432. switch (total) {
  61433. case 0:
  61434. result.push(vertices[index]);
  61435. result.push(vertices[index + 1]);
  61436. result.push(vertices[index + 2]);
  61437. break;
  61438. case 1:
  61439. if (v1Out) {
  61440. nV1 = vertices[index + 1];
  61441. nV2 = vertices[index + 2];
  61442. nV3 = clipVertices(vertices[index], nV1);
  61443. nV4 = clipVertices(vertices[index], nV2);
  61444. }
  61445. if (v2Out) {
  61446. nV1 = vertices[index];
  61447. nV2 = vertices[index + 2];
  61448. nV3 = clipVertices(vertices[index + 1], nV1);
  61449. nV4 = clipVertices(vertices[index + 1], nV2);
  61450. result.push(nV3);
  61451. result.push(nV2.clone());
  61452. result.push(nV1.clone());
  61453. result.push(nV2.clone());
  61454. result.push(nV3.clone());
  61455. result.push(nV4);
  61456. break;
  61457. }
  61458. if (v3Out) {
  61459. nV1 = vertices[index];
  61460. nV2 = vertices[index + 1];
  61461. nV3 = clipVertices(vertices[index + 2], nV1);
  61462. nV4 = clipVertices(vertices[index + 2], nV2);
  61463. }
  61464. if (nV1 && nV2 && nV3 && nV4) {
  61465. result.push(nV1.clone());
  61466. result.push(nV2.clone());
  61467. result.push(nV3);
  61468. result.push(nV4);
  61469. result.push(nV3.clone());
  61470. result.push(nV2.clone());
  61471. }
  61472. break;
  61473. case 2:
  61474. if (!v1Out) {
  61475. nV1 = vertices[index].clone();
  61476. nV2 = clipVertices(nV1, vertices[index + 1]);
  61477. nV3 = clipVertices(nV1, vertices[index + 2]);
  61478. result.push(nV1);
  61479. result.push(nV2);
  61480. result.push(nV3);
  61481. }
  61482. if (!v2Out) {
  61483. nV1 = vertices[index + 1].clone();
  61484. nV2 = clipVertices(nV1, vertices[index + 2]);
  61485. nV3 = clipVertices(nV1, vertices[index]);
  61486. result.push(nV1);
  61487. result.push(nV2);
  61488. result.push(nV3);
  61489. }
  61490. if (!v3Out) {
  61491. nV1 = vertices[index + 2].clone();
  61492. nV2 = clipVertices(nV1, vertices[index]);
  61493. nV3 = clipVertices(nV1, vertices[index + 1]);
  61494. result.push(nV1);
  61495. result.push(nV2);
  61496. result.push(nV3);
  61497. }
  61498. break;
  61499. case 3:
  61500. break;
  61501. }
  61502. }
  61503. return result;
  61504. };
  61505. for (var index = 0; index < indices.length; index += 3) {
  61506. var faceVertices = new Array();
  61507. faceVertices.push(extractDecalVector3(index));
  61508. faceVertices.push(extractDecalVector3(index + 1));
  61509. faceVertices.push(extractDecalVector3(index + 2));
  61510. // Clip
  61511. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61512. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61513. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61514. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61515. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61516. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61517. if (faceVertices.length === 0) {
  61518. continue;
  61519. }
  61520. // Add UVs and get back to world
  61521. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61522. var vertex = faceVertices[vIndex];
  61523. //TODO check for Int32Array | Uint32Array | Uint16Array
  61524. vertexData.indices.push(currentVertexDataIndex);
  61525. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61526. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61527. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61528. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61529. currentVertexDataIndex++;
  61530. }
  61531. }
  61532. // Return mesh
  61533. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61534. vertexData.applyToMesh(decal);
  61535. decal.position = position.clone();
  61536. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61537. return decal;
  61538. };
  61539. // Privates
  61540. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61541. // extrusion geometry
  61542. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61543. var tangents = path3D.getTangents();
  61544. var normals = path3D.getNormals();
  61545. var binormals = path3D.getBinormals();
  61546. var distances = path3D.getDistances();
  61547. var angle = 0;
  61548. var returnScale = function () { return scale !== null ? scale : 1; };
  61549. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61550. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61551. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61552. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61553. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61554. for (var i = 0; i < curve.length; i++) {
  61555. var shapePath = new Array();
  61556. var angleStep = rotate(i, distances[i]);
  61557. var scaleRatio = scl(i, distances[i]);
  61558. for (var p = 0; p < shape.length; p++) {
  61559. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61560. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61561. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61562. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61563. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61564. shapePath[p] = rotated;
  61565. }
  61566. shapePaths[index] = shapePath;
  61567. angle += angleStep;
  61568. index++;
  61569. }
  61570. // cap
  61571. var capPath = function (shapePath) {
  61572. var pointCap = Array();
  61573. var barycenter = BABYLON.Vector3.Zero();
  61574. var i;
  61575. for (i = 0; i < shapePath.length; i++) {
  61576. barycenter.addInPlace(shapePath[i]);
  61577. }
  61578. barycenter.scaleInPlace(1.0 / shapePath.length);
  61579. for (i = 0; i < shapePath.length; i++) {
  61580. pointCap.push(barycenter);
  61581. }
  61582. return pointCap;
  61583. };
  61584. switch (cap) {
  61585. case BABYLON.Mesh.NO_CAP:
  61586. break;
  61587. case BABYLON.Mesh.CAP_START:
  61588. shapePaths[0] = capPath(shapePaths[2]);
  61589. shapePaths[1] = shapePaths[2];
  61590. break;
  61591. case BABYLON.Mesh.CAP_END:
  61592. shapePaths[index] = shapePaths[index - 1];
  61593. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61594. break;
  61595. case BABYLON.Mesh.CAP_ALL:
  61596. shapePaths[0] = capPath(shapePaths[2]);
  61597. shapePaths[1] = shapePaths[2];
  61598. shapePaths[index] = shapePaths[index - 1];
  61599. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61600. break;
  61601. default:
  61602. break;
  61603. }
  61604. return shapePaths;
  61605. };
  61606. var path3D;
  61607. var pathArray;
  61608. if (instance) { // instance update
  61609. path3D = (instance.path3D).update(curve);
  61610. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61611. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61612. return instance;
  61613. }
  61614. // extruded shape creation
  61615. path3D = new BABYLON.Path3D(curve);
  61616. var newShapePaths = new Array();
  61617. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61618. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61619. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61620. extrudedGeneric.pathArray = pathArray;
  61621. extrudedGeneric.path3D = path3D;
  61622. extrudedGeneric.cap = cap;
  61623. return extrudedGeneric;
  61624. };
  61625. return MeshBuilder;
  61626. }());
  61627. BABYLON.MeshBuilder = MeshBuilder;
  61628. })(BABYLON || (BABYLON = {}));
  61629. //# sourceMappingURL=babylon.meshBuilder.js.map
  61630. var BABYLON;
  61631. (function (BABYLON) {
  61632. /**
  61633. * Draco compression (https://google.github.io/draco/)
  61634. *
  61635. * This class wraps the Draco module.
  61636. *
  61637. * **Encoder**
  61638. *
  61639. * The encoder is not currently implemented.
  61640. *
  61641. * **Decoder**
  61642. *
  61643. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61644. *
  61645. * To update the configuration, use the following code:
  61646. * ```javascript
  61647. * BABYLON.DracoCompression.Configuration = {
  61648. * decoder: {
  61649. * wasmUrl: "<url to the WebAssembly library>",
  61650. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61651. * fallbackUrl: "<url to the fallback JavaScript library>",
  61652. * }
  61653. * };
  61654. * ```
  61655. *
  61656. * 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.
  61657. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61658. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61659. *
  61660. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61661. * ```javascript
  61662. * var dracoCompression = new BABYLON.DracoCompression();
  61663. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61664. * [BABYLON.VertexBuffer.PositionKind]: 0
  61665. * });
  61666. * ```
  61667. *
  61668. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61669. */
  61670. var DracoCompression = /** @class */ (function () {
  61671. /**
  61672. * Constructor
  61673. */
  61674. function DracoCompression() {
  61675. }
  61676. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61677. /**
  61678. * Returns true if the decoder is available.
  61679. */
  61680. get: function () {
  61681. if (typeof DracoDecoderModule !== "undefined") {
  61682. return true;
  61683. }
  61684. var decoder = DracoCompression.Configuration.decoder;
  61685. if (decoder) {
  61686. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61687. return true;
  61688. }
  61689. if (decoder.fallbackUrl) {
  61690. return true;
  61691. }
  61692. }
  61693. return false;
  61694. },
  61695. enumerable: true,
  61696. configurable: true
  61697. });
  61698. /**
  61699. * Stop all async operations and release resources.
  61700. */
  61701. DracoCompression.prototype.dispose = function () {
  61702. };
  61703. /**
  61704. * Decode Draco compressed mesh data to vertex data.
  61705. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61706. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61707. * @returns A promise that resolves with the decoded vertex data
  61708. */
  61709. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61710. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61711. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61712. var module = wrappedModule.module;
  61713. var vertexData = new BABYLON.VertexData();
  61714. var buffer = new module.DecoderBuffer();
  61715. buffer.Init(dataView, dataView.byteLength);
  61716. var decoder = new module.Decoder();
  61717. var geometry;
  61718. var status;
  61719. try {
  61720. var type = decoder.GetEncodedGeometryType(buffer);
  61721. switch (type) {
  61722. case module.TRIANGULAR_MESH:
  61723. geometry = new module.Mesh();
  61724. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61725. break;
  61726. case module.POINT_CLOUD:
  61727. geometry = new module.PointCloud();
  61728. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61729. break;
  61730. default:
  61731. throw new Error("Invalid geometry type " + type);
  61732. }
  61733. if (!status.ok() || !geometry.ptr) {
  61734. throw new Error(status.error_msg());
  61735. }
  61736. var numPoints = geometry.num_points();
  61737. if (type === module.TRIANGULAR_MESH) {
  61738. var numFaces = geometry.num_faces();
  61739. var faceIndices = new module.DracoInt32Array();
  61740. try {
  61741. var indices = new Uint32Array(numFaces * 3);
  61742. for (var i = 0; i < numFaces; i++) {
  61743. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61744. var offset = i * 3;
  61745. indices[offset + 0] = faceIndices.GetValue(0);
  61746. indices[offset + 1] = faceIndices.GetValue(1);
  61747. indices[offset + 2] = faceIndices.GetValue(2);
  61748. }
  61749. vertexData.indices = indices;
  61750. }
  61751. finally {
  61752. module.destroy(faceIndices);
  61753. }
  61754. }
  61755. for (var kind in attributes) {
  61756. var uniqueId = attributes[kind];
  61757. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61758. var dracoData = new module.DracoFloat32Array();
  61759. try {
  61760. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61761. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61762. for (var i = 0; i < babylonData.length; i++) {
  61763. babylonData[i] = dracoData.GetValue(i);
  61764. }
  61765. vertexData.set(babylonData, kind);
  61766. }
  61767. finally {
  61768. module.destroy(dracoData);
  61769. }
  61770. }
  61771. }
  61772. finally {
  61773. if (geometry) {
  61774. module.destroy(geometry);
  61775. }
  61776. module.destroy(decoder);
  61777. module.destroy(buffer);
  61778. }
  61779. return vertexData;
  61780. });
  61781. };
  61782. DracoCompression._GetDecoderModule = function () {
  61783. if (!DracoCompression._DecoderModulePromise) {
  61784. var promise = null;
  61785. var config_1 = {};
  61786. if (typeof DracoDecoderModule !== "undefined") {
  61787. promise = Promise.resolve();
  61788. }
  61789. else {
  61790. var decoder = DracoCompression.Configuration.decoder;
  61791. if (decoder) {
  61792. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61793. promise = Promise.all([
  61794. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61795. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61796. config_1.wasmBinary = data;
  61797. })
  61798. ]);
  61799. }
  61800. else if (decoder.fallbackUrl) {
  61801. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61802. }
  61803. }
  61804. }
  61805. if (!promise) {
  61806. throw new Error("Draco decoder module is not available");
  61807. }
  61808. DracoCompression._DecoderModulePromise = promise.then(function () {
  61809. return new Promise(function (resolve) {
  61810. config_1.onModuleLoaded = function (decoderModule) {
  61811. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61812. resolve({ module: decoderModule });
  61813. };
  61814. DracoDecoderModule(config_1);
  61815. });
  61816. });
  61817. }
  61818. return DracoCompression._DecoderModulePromise;
  61819. };
  61820. DracoCompression._LoadScriptAsync = function (url) {
  61821. return new Promise(function (resolve, reject) {
  61822. BABYLON.Tools.LoadScript(url, function () {
  61823. resolve();
  61824. }, function (message) {
  61825. reject(new Error(message));
  61826. });
  61827. });
  61828. };
  61829. DracoCompression._LoadFileAsync = function (url) {
  61830. return new Promise(function (resolve, reject) {
  61831. BABYLON.Tools.LoadFile(url, function (data) {
  61832. resolve(data);
  61833. }, undefined, undefined, true, function (request, exception) {
  61834. reject(exception);
  61835. });
  61836. });
  61837. };
  61838. /**
  61839. * The configuration. Defaults to the following urls:
  61840. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61841. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61842. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61843. */
  61844. DracoCompression.Configuration = {
  61845. decoder: {
  61846. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61847. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61848. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61849. }
  61850. };
  61851. return DracoCompression;
  61852. }());
  61853. BABYLON.DracoCompression = DracoCompression;
  61854. })(BABYLON || (BABYLON = {}));
  61855. //# sourceMappingURL=babylon.dracoCompression.js.map
  61856. var BABYLON;
  61857. (function (BABYLON) {
  61858. var AudioEngine = /** @class */ (function () {
  61859. function AudioEngine() {
  61860. this._audioContext = null;
  61861. this._audioContextInitialized = false;
  61862. this.canUseWebAudio = false;
  61863. this.WarnedWebAudioUnsupported = false;
  61864. this.unlocked = false;
  61865. this.isMP3supported = false;
  61866. this.isOGGsupported = false;
  61867. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61868. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61869. this.canUseWebAudio = true;
  61870. }
  61871. var audioElem = document.createElement('audio');
  61872. try {
  61873. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61874. this.isMP3supported = true;
  61875. }
  61876. }
  61877. catch (e) {
  61878. // protect error during capability check.
  61879. }
  61880. try {
  61881. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61882. this.isOGGsupported = true;
  61883. }
  61884. }
  61885. catch (e) {
  61886. // protect error during capability check.
  61887. }
  61888. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61889. this._unlockiOSaudio();
  61890. }
  61891. else {
  61892. this.unlocked = true;
  61893. }
  61894. }
  61895. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61896. get: function () {
  61897. if (!this._audioContextInitialized) {
  61898. this._initializeAudioContext();
  61899. }
  61900. return this._audioContext;
  61901. },
  61902. enumerable: true,
  61903. configurable: true
  61904. });
  61905. AudioEngine.prototype._unlockiOSaudio = function () {
  61906. var _this = this;
  61907. var unlockaudio = function () {
  61908. if (!_this.audioContext) {
  61909. return;
  61910. }
  61911. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61912. var source = _this.audioContext.createBufferSource();
  61913. source.buffer = buffer;
  61914. source.connect(_this.audioContext.destination);
  61915. source.start(0);
  61916. setTimeout(function () {
  61917. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61918. _this.unlocked = true;
  61919. window.removeEventListener('touchend', unlockaudio, false);
  61920. if (_this.onAudioUnlocked) {
  61921. _this.onAudioUnlocked();
  61922. }
  61923. }
  61924. }, 0);
  61925. };
  61926. window.addEventListener('touchend', unlockaudio, false);
  61927. };
  61928. AudioEngine.prototype._initializeAudioContext = function () {
  61929. try {
  61930. if (this.canUseWebAudio) {
  61931. this._audioContext = new AudioContext();
  61932. // create a global volume gain node
  61933. this.masterGain = this._audioContext.createGain();
  61934. this.masterGain.gain.value = 1;
  61935. this.masterGain.connect(this._audioContext.destination);
  61936. this._audioContextInitialized = true;
  61937. }
  61938. }
  61939. catch (e) {
  61940. this.canUseWebAudio = false;
  61941. BABYLON.Tools.Error("Web Audio: " + e.message);
  61942. }
  61943. };
  61944. AudioEngine.prototype.dispose = function () {
  61945. if (this.canUseWebAudio && this._audioContextInitialized) {
  61946. if (this._connectedAnalyser && this._audioContext) {
  61947. this._connectedAnalyser.stopDebugCanvas();
  61948. this._connectedAnalyser.dispose();
  61949. this.masterGain.disconnect();
  61950. this.masterGain.connect(this._audioContext.destination);
  61951. this._connectedAnalyser = null;
  61952. }
  61953. this.masterGain.gain.value = 1;
  61954. }
  61955. this.WarnedWebAudioUnsupported = false;
  61956. };
  61957. AudioEngine.prototype.getGlobalVolume = function () {
  61958. if (this.canUseWebAudio && this._audioContextInitialized) {
  61959. return this.masterGain.gain.value;
  61960. }
  61961. else {
  61962. return -1;
  61963. }
  61964. };
  61965. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61966. if (this.canUseWebAudio && this._audioContextInitialized) {
  61967. this.masterGain.gain.value = newVolume;
  61968. }
  61969. };
  61970. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61971. if (this._connectedAnalyser) {
  61972. this._connectedAnalyser.stopDebugCanvas();
  61973. }
  61974. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61975. this._connectedAnalyser = analyser;
  61976. this.masterGain.disconnect();
  61977. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61978. }
  61979. };
  61980. return AudioEngine;
  61981. }());
  61982. BABYLON.AudioEngine = AudioEngine;
  61983. })(BABYLON || (BABYLON = {}));
  61984. //# sourceMappingURL=babylon.audioEngine.js.map
  61985. var BABYLON;
  61986. (function (BABYLON) {
  61987. var Sound = /** @class */ (function () {
  61988. /**
  61989. * Create a sound and attach it to a scene
  61990. * @param name Name of your sound
  61991. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  61992. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61993. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61994. */
  61995. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61996. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61997. var _this = this;
  61998. this.autoplay = false;
  61999. this.loop = false;
  62000. this.useCustomAttenuation = false;
  62001. this.spatialSound = false;
  62002. this.refDistance = 1;
  62003. this.rolloffFactor = 1;
  62004. this.maxDistance = 100;
  62005. this.distanceModel = "linear";
  62006. this._panningModel = "equalpower";
  62007. this._playbackRate = 1;
  62008. this._streaming = false;
  62009. this._startTime = 0;
  62010. this._startOffset = 0;
  62011. this._position = BABYLON.Vector3.Zero();
  62012. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62013. this._volume = 1;
  62014. this._isReadyToPlay = false;
  62015. this.isPlaying = false;
  62016. this.isPaused = false;
  62017. this._isDirectional = false;
  62018. // Used if you'd like to create a directional sound.
  62019. // If not set, the sound will be omnidirectional
  62020. this._coneInnerAngle = 360;
  62021. this._coneOuterAngle = 360;
  62022. this._coneOuterGain = 0;
  62023. this._isOutputConnected = false;
  62024. this._urlType = "Unknown";
  62025. this.name = name;
  62026. this._scene = scene;
  62027. this._readyToPlayCallback = readyToPlayCallback;
  62028. // Default custom attenuation function is a linear attenuation
  62029. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62030. if (currentDistance < maxDistance) {
  62031. return currentVolume * (1 - currentDistance / maxDistance);
  62032. }
  62033. else {
  62034. return 0;
  62035. }
  62036. };
  62037. if (options) {
  62038. this.autoplay = options.autoplay || false;
  62039. this.loop = options.loop || false;
  62040. // if volume === 0, we need another way to check this option
  62041. if (options.volume !== undefined) {
  62042. this._volume = options.volume;
  62043. }
  62044. this.spatialSound = options.spatialSound || false;
  62045. this.maxDistance = options.maxDistance || 100;
  62046. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62047. this.rolloffFactor = options.rolloffFactor || 1;
  62048. this.refDistance = options.refDistance || 1;
  62049. this.distanceModel = options.distanceModel || "linear";
  62050. this._playbackRate = options.playbackRate || 1;
  62051. this._streaming = options.streaming || false;
  62052. }
  62053. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62054. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62055. this._soundGain.gain.value = this._volume;
  62056. this._inputAudioNode = this._soundGain;
  62057. this._ouputAudioNode = this._soundGain;
  62058. if (this.spatialSound) {
  62059. this._createSpatialParameters();
  62060. }
  62061. this._scene.mainSoundTrack.AddSound(this);
  62062. var validParameter = true;
  62063. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62064. if (urlOrArrayBuffer) {
  62065. try {
  62066. if (typeof (urlOrArrayBuffer) === "string") {
  62067. this._urlType = "String";
  62068. }
  62069. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62070. this._urlType = "ArrayBuffer";
  62071. }
  62072. else if (urlOrArrayBuffer instanceof MediaStream) {
  62073. this._urlType = "MediaStream";
  62074. }
  62075. else if (Array.isArray(urlOrArrayBuffer)) {
  62076. this._urlType = "Array";
  62077. }
  62078. var urls = [];
  62079. var codecSupportedFound = false;
  62080. switch (this._urlType) {
  62081. case "MediaStream":
  62082. this._streaming = true;
  62083. this._isReadyToPlay = true;
  62084. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62085. if (this.autoplay) {
  62086. this.play();
  62087. }
  62088. if (this._readyToPlayCallback) {
  62089. this._readyToPlayCallback();
  62090. }
  62091. break;
  62092. case "ArrayBuffer":
  62093. if (urlOrArrayBuffer.byteLength > 0) {
  62094. codecSupportedFound = true;
  62095. this._soundLoaded(urlOrArrayBuffer);
  62096. }
  62097. break;
  62098. case "String":
  62099. urls.push(urlOrArrayBuffer);
  62100. case "Array":
  62101. if (urls.length === 0)
  62102. urls = urlOrArrayBuffer;
  62103. // If we found a supported format, we load it immediately and stop the loop
  62104. for (var i = 0; i < urls.length; i++) {
  62105. var url = urls[i];
  62106. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62107. codecSupportedFound = true;
  62108. }
  62109. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62110. codecSupportedFound = true;
  62111. }
  62112. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62113. codecSupportedFound = true;
  62114. }
  62115. if (url.indexOf("blob:") !== -1) {
  62116. codecSupportedFound = true;
  62117. }
  62118. if (codecSupportedFound) {
  62119. // Loading sound using XHR2
  62120. if (!this._streaming) {
  62121. this._scene._loadFile(url, function (data) {
  62122. _this._soundLoaded(data);
  62123. }, undefined, true, true, function (exception) {
  62124. if (exception) {
  62125. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62126. }
  62127. BABYLON.Tools.Error("Sound creation aborted.");
  62128. _this._scene.mainSoundTrack.RemoveSound(_this);
  62129. });
  62130. }
  62131. // Streaming sound using HTML5 Audio tag
  62132. else {
  62133. this._htmlAudioElement = new Audio(url);
  62134. this._htmlAudioElement.controls = false;
  62135. this._htmlAudioElement.loop = this.loop;
  62136. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62137. this._htmlAudioElement.preload = "auto";
  62138. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62139. _this._isReadyToPlay = true;
  62140. if (_this.autoplay) {
  62141. _this.play();
  62142. }
  62143. if (_this._readyToPlayCallback) {
  62144. _this._readyToPlayCallback();
  62145. }
  62146. });
  62147. document.body.appendChild(this._htmlAudioElement);
  62148. }
  62149. break;
  62150. }
  62151. }
  62152. break;
  62153. default:
  62154. validParameter = false;
  62155. break;
  62156. }
  62157. if (!validParameter) {
  62158. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62159. }
  62160. else {
  62161. if (!codecSupportedFound) {
  62162. this._isReadyToPlay = true;
  62163. // Simulating a ready to play event to avoid breaking code path
  62164. if (this._readyToPlayCallback) {
  62165. window.setTimeout(function () {
  62166. if (_this._readyToPlayCallback) {
  62167. _this._readyToPlayCallback();
  62168. }
  62169. }, 1000);
  62170. }
  62171. }
  62172. }
  62173. }
  62174. catch (ex) {
  62175. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62176. this._scene.mainSoundTrack.RemoveSound(this);
  62177. }
  62178. }
  62179. }
  62180. else {
  62181. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62182. this._scene.mainSoundTrack.AddSound(this);
  62183. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62184. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62185. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62186. }
  62187. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62188. if (this._readyToPlayCallback) {
  62189. window.setTimeout(function () {
  62190. if (_this._readyToPlayCallback) {
  62191. _this._readyToPlayCallback();
  62192. }
  62193. }, 1000);
  62194. }
  62195. }
  62196. }
  62197. Sound.prototype.dispose = function () {
  62198. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62199. if (this.isPlaying) {
  62200. this.stop();
  62201. }
  62202. this._isReadyToPlay = false;
  62203. if (this.soundTrackId === -1) {
  62204. this._scene.mainSoundTrack.RemoveSound(this);
  62205. }
  62206. else {
  62207. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62208. }
  62209. if (this._soundGain) {
  62210. this._soundGain.disconnect();
  62211. this._soundGain = null;
  62212. }
  62213. if (this._soundPanner) {
  62214. this._soundPanner.disconnect();
  62215. this._soundPanner = null;
  62216. }
  62217. if (this._soundSource) {
  62218. this._soundSource.disconnect();
  62219. this._soundSource = null;
  62220. }
  62221. this._audioBuffer = null;
  62222. if (this._htmlAudioElement) {
  62223. this._htmlAudioElement.pause();
  62224. this._htmlAudioElement.src = "";
  62225. document.body.removeChild(this._htmlAudioElement);
  62226. }
  62227. if (this._streamingSource) {
  62228. this._streamingSource.disconnect();
  62229. }
  62230. if (this._connectedMesh && this._registerFunc) {
  62231. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62232. this._connectedMesh = null;
  62233. }
  62234. }
  62235. };
  62236. Sound.prototype.isReady = function () {
  62237. return this._isReadyToPlay;
  62238. };
  62239. Sound.prototype._soundLoaded = function (audioData) {
  62240. var _this = this;
  62241. if (!BABYLON.Engine.audioEngine.audioContext) {
  62242. return;
  62243. }
  62244. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62245. _this._audioBuffer = buffer;
  62246. _this._isReadyToPlay = true;
  62247. if (_this.autoplay) {
  62248. _this.play();
  62249. }
  62250. if (_this._readyToPlayCallback) {
  62251. _this._readyToPlayCallback();
  62252. }
  62253. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62254. };
  62255. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62256. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62257. this._audioBuffer = audioBuffer;
  62258. this._isReadyToPlay = true;
  62259. }
  62260. };
  62261. Sound.prototype.updateOptions = function (options) {
  62262. if (options) {
  62263. this.loop = options.loop || this.loop;
  62264. this.maxDistance = options.maxDistance || this.maxDistance;
  62265. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62266. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62267. this.refDistance = options.refDistance || this.refDistance;
  62268. this.distanceModel = options.distanceModel || this.distanceModel;
  62269. this._playbackRate = options.playbackRate || this._playbackRate;
  62270. this._updateSpatialParameters();
  62271. if (this.isPlaying) {
  62272. if (this._streaming && this._htmlAudioElement) {
  62273. this._htmlAudioElement.playbackRate = this._playbackRate;
  62274. }
  62275. else {
  62276. if (this._soundSource) {
  62277. this._soundSource.playbackRate.value = this._playbackRate;
  62278. }
  62279. }
  62280. }
  62281. }
  62282. };
  62283. Sound.prototype._createSpatialParameters = function () {
  62284. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62285. if (this._scene.headphone) {
  62286. this._panningModel = "HRTF";
  62287. }
  62288. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62289. this._updateSpatialParameters();
  62290. this._soundPanner.connect(this._ouputAudioNode);
  62291. this._inputAudioNode = this._soundPanner;
  62292. }
  62293. };
  62294. Sound.prototype._updateSpatialParameters = function () {
  62295. if (this.spatialSound && this._soundPanner) {
  62296. if (this.useCustomAttenuation) {
  62297. // Tricks to disable in a way embedded Web Audio attenuation
  62298. this._soundPanner.distanceModel = "linear";
  62299. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62300. this._soundPanner.refDistance = 1;
  62301. this._soundPanner.rolloffFactor = 1;
  62302. this._soundPanner.panningModel = this._panningModel;
  62303. }
  62304. else {
  62305. this._soundPanner.distanceModel = this.distanceModel;
  62306. this._soundPanner.maxDistance = this.maxDistance;
  62307. this._soundPanner.refDistance = this.refDistance;
  62308. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62309. this._soundPanner.panningModel = this._panningModel;
  62310. }
  62311. }
  62312. };
  62313. Sound.prototype.switchPanningModelToHRTF = function () {
  62314. this._panningModel = "HRTF";
  62315. this._switchPanningModel();
  62316. };
  62317. Sound.prototype.switchPanningModelToEqualPower = function () {
  62318. this._panningModel = "equalpower";
  62319. this._switchPanningModel();
  62320. };
  62321. Sound.prototype._switchPanningModel = function () {
  62322. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62323. this._soundPanner.panningModel = this._panningModel;
  62324. }
  62325. };
  62326. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62328. if (this._isOutputConnected) {
  62329. this._ouputAudioNode.disconnect();
  62330. }
  62331. this._ouputAudioNode.connect(soundTrackAudioNode);
  62332. this._isOutputConnected = true;
  62333. }
  62334. };
  62335. /**
  62336. * Transform this sound into a directional source
  62337. * @param coneInnerAngle Size of the inner cone in degree
  62338. * @param coneOuterAngle Size of the outer cone in degree
  62339. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62340. */
  62341. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62342. if (coneOuterAngle < coneInnerAngle) {
  62343. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62344. return;
  62345. }
  62346. this._coneInnerAngle = coneInnerAngle;
  62347. this._coneOuterAngle = coneOuterAngle;
  62348. this._coneOuterGain = coneOuterGain;
  62349. this._isDirectional = true;
  62350. if (this.isPlaying && this.loop) {
  62351. this.stop();
  62352. this.play();
  62353. }
  62354. };
  62355. Sound.prototype.setPosition = function (newPosition) {
  62356. this._position = newPosition;
  62357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62358. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62359. }
  62360. };
  62361. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62362. this._localDirection = newLocalDirection;
  62363. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62364. this._updateDirection();
  62365. }
  62366. };
  62367. Sound.prototype._updateDirection = function () {
  62368. if (!this._connectedMesh || !this._soundPanner) {
  62369. return;
  62370. }
  62371. var mat = this._connectedMesh.getWorldMatrix();
  62372. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62373. direction.normalize();
  62374. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62375. };
  62376. Sound.prototype.updateDistanceFromListener = function () {
  62377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62378. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62379. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62380. }
  62381. };
  62382. Sound.prototype.setAttenuationFunction = function (callback) {
  62383. this._customAttenuationFunction = callback;
  62384. };
  62385. /**
  62386. * Play the sound
  62387. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62388. * @param offset (optional) Start the sound setting it at a specific time
  62389. */
  62390. Sound.prototype.play = function (time, offset) {
  62391. var _this = this;
  62392. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62393. try {
  62394. if (this._startOffset < 0) {
  62395. time = -this._startOffset;
  62396. this._startOffset = 0;
  62397. }
  62398. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62399. if (!this._soundSource || !this._streamingSource) {
  62400. if (this.spatialSound && this._soundPanner) {
  62401. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62402. if (this._isDirectional) {
  62403. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62404. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62405. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62406. if (this._connectedMesh) {
  62407. this._updateDirection();
  62408. }
  62409. else {
  62410. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62411. }
  62412. }
  62413. }
  62414. }
  62415. if (this._streaming) {
  62416. if (!this._streamingSource) {
  62417. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62418. this._htmlAudioElement.onended = function () { _this._onended(); };
  62419. this._htmlAudioElement.playbackRate = this._playbackRate;
  62420. }
  62421. this._streamingSource.disconnect();
  62422. this._streamingSource.connect(this._inputAudioNode);
  62423. if (this._htmlAudioElement) {
  62424. this._htmlAudioElement.play();
  62425. }
  62426. }
  62427. else {
  62428. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62429. this._soundSource.buffer = this._audioBuffer;
  62430. this._soundSource.connect(this._inputAudioNode);
  62431. this._soundSource.loop = this.loop;
  62432. this._soundSource.playbackRate.value = this._playbackRate;
  62433. this._soundSource.onended = function () { _this._onended(); };
  62434. if (this._soundSource.buffer) {
  62435. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62436. }
  62437. }
  62438. this._startTime = startTime;
  62439. this.isPlaying = true;
  62440. this.isPaused = false;
  62441. }
  62442. catch (ex) {
  62443. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62444. }
  62445. }
  62446. };
  62447. Sound.prototype._onended = function () {
  62448. this.isPlaying = false;
  62449. if (this.onended) {
  62450. this.onended();
  62451. }
  62452. };
  62453. /**
  62454. * Stop the sound
  62455. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62456. */
  62457. Sound.prototype.stop = function (time) {
  62458. if (this.isPlaying) {
  62459. if (this._streaming) {
  62460. if (this._htmlAudioElement) {
  62461. this._htmlAudioElement.pause();
  62462. // Test needed for Firefox or it will generate an Invalid State Error
  62463. if (this._htmlAudioElement.currentTime > 0) {
  62464. this._htmlAudioElement.currentTime = 0;
  62465. }
  62466. }
  62467. else {
  62468. this._streamingSource.disconnect();
  62469. }
  62470. }
  62471. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62472. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62473. this._soundSource.stop(stopTime);
  62474. this._soundSource.onended = function () { };
  62475. if (!this.isPaused) {
  62476. this._startOffset = 0;
  62477. }
  62478. }
  62479. this.isPlaying = false;
  62480. }
  62481. };
  62482. Sound.prototype.pause = function () {
  62483. if (this.isPlaying) {
  62484. this.isPaused = true;
  62485. if (this._streaming) {
  62486. if (this._htmlAudioElement) {
  62487. this._htmlAudioElement.pause();
  62488. }
  62489. else {
  62490. this._streamingSource.disconnect();
  62491. }
  62492. }
  62493. else if (BABYLON.Engine.audioEngine.audioContext) {
  62494. this.stop(0);
  62495. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62496. }
  62497. }
  62498. };
  62499. Sound.prototype.setVolume = function (newVolume, time) {
  62500. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62501. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62502. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62503. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62504. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62505. }
  62506. else {
  62507. this._soundGain.gain.value = newVolume;
  62508. }
  62509. }
  62510. this._volume = newVolume;
  62511. };
  62512. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62513. this._playbackRate = newPlaybackRate;
  62514. if (this.isPlaying) {
  62515. if (this._streaming && this._htmlAudioElement) {
  62516. this._htmlAudioElement.playbackRate = this._playbackRate;
  62517. }
  62518. else if (this._soundSource) {
  62519. this._soundSource.playbackRate.value = this._playbackRate;
  62520. }
  62521. }
  62522. };
  62523. Sound.prototype.getVolume = function () {
  62524. return this._volume;
  62525. };
  62526. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62527. var _this = this;
  62528. if (this._connectedMesh && this._registerFunc) {
  62529. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62530. this._registerFunc = null;
  62531. }
  62532. this._connectedMesh = meshToConnectTo;
  62533. if (!this.spatialSound) {
  62534. this.spatialSound = true;
  62535. this._createSpatialParameters();
  62536. if (this.isPlaying && this.loop) {
  62537. this.stop();
  62538. this.play();
  62539. }
  62540. }
  62541. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62542. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62543. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62544. };
  62545. Sound.prototype.detachFromMesh = function () {
  62546. if (this._connectedMesh && this._registerFunc) {
  62547. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62548. this._registerFunc = null;
  62549. this._connectedMesh = null;
  62550. }
  62551. };
  62552. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62553. if (!node.getBoundingInfo) {
  62554. return;
  62555. }
  62556. var mesh = node;
  62557. var boundingInfo = mesh.getBoundingInfo();
  62558. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62559. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62560. this._updateDirection();
  62561. }
  62562. };
  62563. Sound.prototype.clone = function () {
  62564. var _this = this;
  62565. if (!this._streaming) {
  62566. var setBufferAndRun = function () {
  62567. if (_this._isReadyToPlay) {
  62568. clonedSound._audioBuffer = _this.getAudioBuffer();
  62569. clonedSound._isReadyToPlay = true;
  62570. if (clonedSound.autoplay) {
  62571. clonedSound.play();
  62572. }
  62573. }
  62574. else {
  62575. window.setTimeout(setBufferAndRun, 300);
  62576. }
  62577. };
  62578. var currentOptions = {
  62579. autoplay: this.autoplay, loop: this.loop,
  62580. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62581. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62582. refDistance: this.refDistance, distanceModel: this.distanceModel
  62583. };
  62584. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62585. if (this.useCustomAttenuation) {
  62586. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62587. }
  62588. clonedSound.setPosition(this._position);
  62589. clonedSound.setPlaybackRate(this._playbackRate);
  62590. setBufferAndRun();
  62591. return clonedSound;
  62592. }
  62593. // Can't clone a streaming sound
  62594. else {
  62595. return null;
  62596. }
  62597. };
  62598. Sound.prototype.getAudioBuffer = function () {
  62599. return this._audioBuffer;
  62600. };
  62601. Sound.prototype.serialize = function () {
  62602. var serializationObject = {
  62603. name: this.name,
  62604. url: this.name,
  62605. autoplay: this.autoplay,
  62606. loop: this.loop,
  62607. volume: this._volume,
  62608. spatialSound: this.spatialSound,
  62609. maxDistance: this.maxDistance,
  62610. rolloffFactor: this.rolloffFactor,
  62611. refDistance: this.refDistance,
  62612. distanceModel: this.distanceModel,
  62613. playbackRate: this._playbackRate,
  62614. panningModel: this._panningModel,
  62615. soundTrackId: this.soundTrackId
  62616. };
  62617. if (this.spatialSound) {
  62618. if (this._connectedMesh)
  62619. serializationObject.connectedMeshId = this._connectedMesh.id;
  62620. serializationObject.position = this._position.asArray();
  62621. serializationObject.refDistance = this.refDistance;
  62622. serializationObject.distanceModel = this.distanceModel;
  62623. serializationObject.isDirectional = this._isDirectional;
  62624. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62625. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62626. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62627. serializationObject.coneOuterGain = this._coneOuterGain;
  62628. }
  62629. return serializationObject;
  62630. };
  62631. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62632. var soundName = parsedSound.name;
  62633. var soundUrl;
  62634. if (parsedSound.url) {
  62635. soundUrl = rootUrl + parsedSound.url;
  62636. }
  62637. else {
  62638. soundUrl = rootUrl + soundName;
  62639. }
  62640. var options = {
  62641. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62642. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62643. rolloffFactor: parsedSound.rolloffFactor,
  62644. refDistance: parsedSound.refDistance,
  62645. distanceModel: parsedSound.distanceModel,
  62646. playbackRate: parsedSound.playbackRate
  62647. };
  62648. var newSound;
  62649. if (!sourceSound) {
  62650. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62651. scene._addPendingData(newSound);
  62652. }
  62653. else {
  62654. var setBufferAndRun = function () {
  62655. if (sourceSound._isReadyToPlay) {
  62656. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62657. newSound._isReadyToPlay = true;
  62658. if (newSound.autoplay) {
  62659. newSound.play();
  62660. }
  62661. }
  62662. else {
  62663. window.setTimeout(setBufferAndRun, 300);
  62664. }
  62665. };
  62666. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62667. setBufferAndRun();
  62668. }
  62669. if (parsedSound.position) {
  62670. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62671. newSound.setPosition(soundPosition);
  62672. }
  62673. if (parsedSound.isDirectional) {
  62674. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62675. if (parsedSound.localDirectionToMesh) {
  62676. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62677. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62678. }
  62679. }
  62680. if (parsedSound.connectedMeshId) {
  62681. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62682. if (connectedMesh) {
  62683. newSound.attachToMesh(connectedMesh);
  62684. }
  62685. }
  62686. return newSound;
  62687. };
  62688. return Sound;
  62689. }());
  62690. BABYLON.Sound = Sound;
  62691. })(BABYLON || (BABYLON = {}));
  62692. //# sourceMappingURL=babylon.sound.js.map
  62693. var BABYLON;
  62694. (function (BABYLON) {
  62695. var SoundTrack = /** @class */ (function () {
  62696. function SoundTrack(scene, options) {
  62697. this.id = -1;
  62698. this._isMainTrack = false;
  62699. this._isInitialized = false;
  62700. this._scene = scene;
  62701. this.soundCollection = new Array();
  62702. this._options = options;
  62703. if (!this._isMainTrack) {
  62704. this._scene.soundTracks.push(this);
  62705. this.id = this._scene.soundTracks.length - 1;
  62706. }
  62707. }
  62708. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62709. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62710. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62711. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62712. if (this._options) {
  62713. if (this._options.volume) {
  62714. this._outputAudioNode.gain.value = this._options.volume;
  62715. }
  62716. if (this._options.mainTrack) {
  62717. this._isMainTrack = this._options.mainTrack;
  62718. }
  62719. }
  62720. this._isInitialized = true;
  62721. }
  62722. };
  62723. SoundTrack.prototype.dispose = function () {
  62724. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62725. if (this._connectedAnalyser) {
  62726. this._connectedAnalyser.stopDebugCanvas();
  62727. }
  62728. while (this.soundCollection.length) {
  62729. this.soundCollection[0].dispose();
  62730. }
  62731. if (this._outputAudioNode) {
  62732. this._outputAudioNode.disconnect();
  62733. }
  62734. this._outputAudioNode = null;
  62735. }
  62736. };
  62737. SoundTrack.prototype.AddSound = function (sound) {
  62738. if (!this._isInitialized) {
  62739. this._initializeSoundTrackAudioGraph();
  62740. }
  62741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62742. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62743. }
  62744. if (sound.soundTrackId) {
  62745. if (sound.soundTrackId === -1) {
  62746. this._scene.mainSoundTrack.RemoveSound(sound);
  62747. }
  62748. else {
  62749. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62750. }
  62751. }
  62752. this.soundCollection.push(sound);
  62753. sound.soundTrackId = this.id;
  62754. };
  62755. SoundTrack.prototype.RemoveSound = function (sound) {
  62756. var index = this.soundCollection.indexOf(sound);
  62757. if (index !== -1) {
  62758. this.soundCollection.splice(index, 1);
  62759. }
  62760. };
  62761. SoundTrack.prototype.setVolume = function (newVolume) {
  62762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62763. this._outputAudioNode.gain.value = newVolume;
  62764. }
  62765. };
  62766. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62767. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62768. for (var i = 0; i < this.soundCollection.length; i++) {
  62769. this.soundCollection[i].switchPanningModelToHRTF();
  62770. }
  62771. }
  62772. };
  62773. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62775. for (var i = 0; i < this.soundCollection.length; i++) {
  62776. this.soundCollection[i].switchPanningModelToEqualPower();
  62777. }
  62778. }
  62779. };
  62780. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62781. if (this._connectedAnalyser) {
  62782. this._connectedAnalyser.stopDebugCanvas();
  62783. }
  62784. this._connectedAnalyser = analyser;
  62785. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62786. this._outputAudioNode.disconnect();
  62787. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62788. }
  62789. };
  62790. return SoundTrack;
  62791. }());
  62792. BABYLON.SoundTrack = SoundTrack;
  62793. })(BABYLON || (BABYLON = {}));
  62794. //# sourceMappingURL=babylon.soundtrack.js.map
  62795. var BABYLON;
  62796. (function (BABYLON) {
  62797. /**
  62798. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62799. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62800. */
  62801. var Analyser = /** @class */ (function () {
  62802. /**
  62803. * Creates a new analyser
  62804. * @param scene defines hosting scene
  62805. */
  62806. function Analyser(scene) {
  62807. /**
  62808. * Gets or sets the smoothing
  62809. * @ignorenaming
  62810. */
  62811. this.SMOOTHING = 0.75;
  62812. /**
  62813. * Gets or sets the FFT table size
  62814. * @ignorenaming
  62815. */
  62816. this.FFT_SIZE = 512;
  62817. /**
  62818. * Gets or sets the bar graph amplitude
  62819. * @ignorenaming
  62820. */
  62821. this.BARGRAPHAMPLITUDE = 256;
  62822. /**
  62823. * Gets or sets the position of the debug canvas
  62824. * @ignorenaming
  62825. */
  62826. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62827. /**
  62828. * Gets or sets the debug canvas size
  62829. * @ignorenaming
  62830. */
  62831. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62832. this._scene = scene;
  62833. this._audioEngine = BABYLON.Engine.audioEngine;
  62834. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62835. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62836. this._webAudioAnalyser.minDecibels = -140;
  62837. this._webAudioAnalyser.maxDecibels = 0;
  62838. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62839. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62840. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62841. }
  62842. }
  62843. /**
  62844. * Get the number of data values you will have to play with for the visualization
  62845. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62846. * @returns a number
  62847. */
  62848. Analyser.prototype.getFrequencyBinCount = function () {
  62849. if (this._audioEngine.canUseWebAudio) {
  62850. return this._webAudioAnalyser.frequencyBinCount;
  62851. }
  62852. else {
  62853. return 0;
  62854. }
  62855. };
  62856. /**
  62857. * Gets the current frequency data as a byte array
  62858. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62859. * @returns a Uint8Array
  62860. */
  62861. Analyser.prototype.getByteFrequencyData = function () {
  62862. if (this._audioEngine.canUseWebAudio) {
  62863. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62864. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62865. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62866. }
  62867. return this._byteFreqs;
  62868. };
  62869. /**
  62870. * Gets the current waveform as a byte array
  62871. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62872. * @returns a Uint8Array
  62873. */
  62874. Analyser.prototype.getByteTimeDomainData = function () {
  62875. if (this._audioEngine.canUseWebAudio) {
  62876. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62877. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62878. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62879. }
  62880. return this._byteTime;
  62881. };
  62882. /**
  62883. * Gets the current frequency data as a float array
  62884. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62885. * @returns a Float32Array
  62886. */
  62887. Analyser.prototype.getFloatFrequencyData = function () {
  62888. if (this._audioEngine.canUseWebAudio) {
  62889. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62890. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62891. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62892. }
  62893. return this._floatFreqs;
  62894. };
  62895. /**
  62896. * Renders the debug canvas
  62897. */
  62898. Analyser.prototype.drawDebugCanvas = function () {
  62899. var _this = this;
  62900. if (this._audioEngine.canUseWebAudio) {
  62901. if (!this._debugCanvas) {
  62902. this._debugCanvas = document.createElement("canvas");
  62903. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62904. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62905. this._debugCanvas.style.position = "absolute";
  62906. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62907. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62908. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62909. document.body.appendChild(this._debugCanvas);
  62910. this._registerFunc = function () {
  62911. _this.drawDebugCanvas();
  62912. };
  62913. this._scene.registerBeforeRender(this._registerFunc);
  62914. }
  62915. if (this._registerFunc && this._debugCanvasContext) {
  62916. var workingArray = this.getByteFrequencyData();
  62917. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62918. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62919. // Draw the frequency domain chart.
  62920. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62921. var value = workingArray[i];
  62922. var percent = value / this.BARGRAPHAMPLITUDE;
  62923. var height = this.DEBUGCANVASSIZE.height * percent;
  62924. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62925. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62926. var hue = i / this.getFrequencyBinCount() * 360;
  62927. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62928. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62929. }
  62930. }
  62931. }
  62932. };
  62933. /**
  62934. * Stops rendering the debug canvas and removes it
  62935. */
  62936. Analyser.prototype.stopDebugCanvas = function () {
  62937. if (this._debugCanvas) {
  62938. if (this._registerFunc) {
  62939. this._scene.unregisterBeforeRender(this._registerFunc);
  62940. this._registerFunc = null;
  62941. }
  62942. document.body.removeChild(this._debugCanvas);
  62943. this._debugCanvas = null;
  62944. this._debugCanvasContext = null;
  62945. }
  62946. };
  62947. /**
  62948. * Connects two audio nodes
  62949. * @param inputAudioNode defines first node to connect
  62950. * @param outputAudioNode defines second node to connect
  62951. */
  62952. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62953. if (this._audioEngine.canUseWebAudio) {
  62954. inputAudioNode.connect(this._webAudioAnalyser);
  62955. this._webAudioAnalyser.connect(outputAudioNode);
  62956. }
  62957. };
  62958. /**
  62959. * Releases all associated resources
  62960. */
  62961. Analyser.prototype.dispose = function () {
  62962. if (this._audioEngine.canUseWebAudio) {
  62963. this._webAudioAnalyser.disconnect();
  62964. }
  62965. };
  62966. return Analyser;
  62967. }());
  62968. BABYLON.Analyser = Analyser;
  62969. })(BABYLON || (BABYLON = {}));
  62970. //# sourceMappingURL=babylon.analyser.js.map
  62971. var BABYLON;
  62972. (function (BABYLON) {
  62973. var CubeTexture = /** @class */ (function (_super) {
  62974. __extends(CubeTexture, _super);
  62975. /**
  62976. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62977. * as prefiltered data.
  62978. * @param rootUrl defines the url of the texture or the root name of the six images
  62979. * @param scene defines the scene the texture is attached to
  62980. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62981. * @param noMipmap defines if mipmaps should be created or not
  62982. * @param files defines the six files to load for the different faces
  62983. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62984. * @param onError defines a callback triggered in case of error during load
  62985. * @param format defines the internal format to use for the texture once loaded
  62986. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62987. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62988. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62989. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62990. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62991. * @return the cube texture
  62992. */
  62993. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62994. if (extensions === void 0) { extensions = null; }
  62995. if (noMipmap === void 0) { noMipmap = false; }
  62996. if (files === void 0) { files = null; }
  62997. if (onLoad === void 0) { onLoad = null; }
  62998. if (onError === void 0) { onError = null; }
  62999. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63000. if (prefiltered === void 0) { prefiltered = false; }
  63001. if (forcedExtension === void 0) { forcedExtension = null; }
  63002. if (createPolynomials === void 0) { createPolynomials = false; }
  63003. if (lodScale === void 0) { lodScale = 0.8; }
  63004. if (lodOffset === void 0) { lodOffset = 0; }
  63005. var _this = _super.call(this, scene) || this;
  63006. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63007. /**
  63008. * Gets or sets the center of the bounding box associated with the cube texture
  63009. * It must define where the camera used to render the texture was set
  63010. */
  63011. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63012. _this._rotationY = 0;
  63013. /** @hidden */
  63014. _this._prefiltered = false;
  63015. _this.name = rootUrl;
  63016. _this.url = rootUrl;
  63017. _this._noMipmap = noMipmap;
  63018. _this.hasAlpha = false;
  63019. _this._format = format;
  63020. _this.isCube = true;
  63021. _this._textureMatrix = BABYLON.Matrix.Identity();
  63022. _this._createPolynomials = createPolynomials;
  63023. if (!rootUrl && !files) {
  63024. return _this;
  63025. }
  63026. var lastDot = rootUrl.lastIndexOf(".");
  63027. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63028. var isDDS = (extension === ".dds");
  63029. var isEnv = (extension === ".env");
  63030. if (isEnv) {
  63031. _this.gammaSpace = false;
  63032. _this._prefiltered = false;
  63033. }
  63034. else {
  63035. _this._prefiltered = prefiltered;
  63036. if (prefiltered) {
  63037. _this.gammaSpace = false;
  63038. }
  63039. }
  63040. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63041. if (!files) {
  63042. if (!isEnv && !isDDS && !extensions) {
  63043. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63044. }
  63045. files = [];
  63046. if (extensions) {
  63047. for (var index = 0; index < extensions.length; index++) {
  63048. files.push(rootUrl + extensions[index]);
  63049. }
  63050. }
  63051. }
  63052. _this._files = files;
  63053. if (!_this._texture) {
  63054. if (!scene.useDelayedTextureLoading) {
  63055. if (prefiltered) {
  63056. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63057. }
  63058. else {
  63059. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63060. }
  63061. }
  63062. else {
  63063. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63064. }
  63065. }
  63066. else if (onLoad) {
  63067. if (_this._texture.isReady) {
  63068. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63069. }
  63070. else {
  63071. _this._texture.onLoadedObservable.add(onLoad);
  63072. }
  63073. }
  63074. return _this;
  63075. }
  63076. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63077. get: function () {
  63078. return this._boundingBoxSize;
  63079. },
  63080. /**
  63081. * Gets or sets the size of the bounding box associated with the cube texture
  63082. * When defined, the cubemap will switch to local mode
  63083. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63084. * @example https://www.babylonjs-playground.com/#RNASML
  63085. */
  63086. set: function (value) {
  63087. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63088. return;
  63089. }
  63090. this._boundingBoxSize = value;
  63091. var scene = this.getScene();
  63092. if (scene) {
  63093. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63094. }
  63095. },
  63096. enumerable: true,
  63097. configurable: true
  63098. });
  63099. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63100. /**
  63101. * Gets texture matrix rotation angle around Y axis radians.
  63102. */
  63103. get: function () {
  63104. return this._rotationY;
  63105. },
  63106. /**
  63107. * Sets texture matrix rotation angle around Y axis in radians.
  63108. */
  63109. set: function (value) {
  63110. this._rotationY = value;
  63111. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63112. },
  63113. enumerable: true,
  63114. configurable: true
  63115. });
  63116. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63117. var rootUrlKey = "";
  63118. files.forEach(function (url) { return rootUrlKey += url; });
  63119. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63120. };
  63121. /**
  63122. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63123. * @param url defines the url of the prefiltered texture
  63124. * @param scene defines the scene the texture is attached to
  63125. * @param forcedExtension defines the extension of the file if different from the url
  63126. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63127. * @return the prefiltered texture
  63128. */
  63129. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63130. if (forcedExtension === void 0) { forcedExtension = null; }
  63131. if (createPolynomials === void 0) { createPolynomials = true; }
  63132. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63133. };
  63134. // Methods
  63135. CubeTexture.prototype.delayLoad = function () {
  63136. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63137. return;
  63138. }
  63139. var scene = this.getScene();
  63140. if (!scene) {
  63141. return;
  63142. }
  63143. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63144. this._texture = this._getFromCache(this.url, this._noMipmap);
  63145. if (!this._texture) {
  63146. if (this._prefiltered) {
  63147. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63148. }
  63149. else {
  63150. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63151. }
  63152. }
  63153. };
  63154. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63155. return this._textureMatrix;
  63156. };
  63157. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63158. this._textureMatrix = value;
  63159. };
  63160. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63161. var texture = BABYLON.SerializationHelper.Parse(function () {
  63162. var prefiltered = false;
  63163. if (parsedTexture.prefiltered) {
  63164. prefiltered = parsedTexture.prefiltered;
  63165. }
  63166. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63167. }, parsedTexture, scene);
  63168. // Local Cubemaps
  63169. if (parsedTexture.boundingBoxPosition) {
  63170. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63171. }
  63172. if (parsedTexture.boundingBoxSize) {
  63173. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63174. }
  63175. // Animations
  63176. if (parsedTexture.animations) {
  63177. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63178. var parsedAnimation = parsedTexture.animations[animationIndex];
  63179. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63180. }
  63181. }
  63182. return texture;
  63183. };
  63184. CubeTexture.prototype.clone = function () {
  63185. var _this = this;
  63186. return BABYLON.SerializationHelper.Clone(function () {
  63187. var scene = _this.getScene();
  63188. if (!scene) {
  63189. return _this;
  63190. }
  63191. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63192. }, this);
  63193. };
  63194. __decorate([
  63195. BABYLON.serialize("rotationY")
  63196. ], CubeTexture.prototype, "_rotationY", void 0);
  63197. return CubeTexture;
  63198. }(BABYLON.BaseTexture));
  63199. BABYLON.CubeTexture = CubeTexture;
  63200. })(BABYLON || (BABYLON = {}));
  63201. //# sourceMappingURL=babylon.cubeTexture.js.map
  63202. var BABYLON;
  63203. (function (BABYLON) {
  63204. var RenderTargetTexture = /** @class */ (function (_super) {
  63205. __extends(RenderTargetTexture, _super);
  63206. /**
  63207. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63208. * or used a shadow, depth texture...
  63209. * @param name The friendly name of the texture
  63210. * @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)
  63211. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63212. * @param generateMipMaps True if mip maps need to be generated after render.
  63213. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63214. * @param type The type of the buffer in the RTT (int, half float, float...)
  63215. * @param isCube True if a cube texture needs to be created
  63216. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63217. * @param generateDepthBuffer True to generate a depth buffer
  63218. * @param generateStencilBuffer True to generate a stencil buffer
  63219. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63220. */
  63221. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63222. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63223. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63224. if (isCube === void 0) { isCube = false; }
  63225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63226. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63227. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63228. if (isMulti === void 0) { isMulti = false; }
  63229. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63230. _this.isCube = isCube;
  63231. /**
  63232. * Use this list to define the list of mesh you want to render.
  63233. */
  63234. _this.renderList = new Array();
  63235. _this.renderParticles = true;
  63236. _this.renderSprites = false;
  63237. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63238. _this.ignoreCameraViewport = false;
  63239. // Events
  63240. /**
  63241. * An event triggered when the texture is unbind.
  63242. */
  63243. _this.onBeforeBindObservable = new BABYLON.Observable();
  63244. /**
  63245. * An event triggered when the texture is unbind.
  63246. */
  63247. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63248. /**
  63249. * An event triggered before rendering the texture
  63250. */
  63251. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63252. /**
  63253. * An event triggered after rendering the texture
  63254. */
  63255. _this.onAfterRenderObservable = new BABYLON.Observable();
  63256. /**
  63257. * An event triggered after the texture clear
  63258. */
  63259. _this.onClearObservable = new BABYLON.Observable();
  63260. _this._currentRefreshId = -1;
  63261. _this._refreshRate = 1;
  63262. _this._samples = 1;
  63263. /**
  63264. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63265. * It must define where the camera used to render the texture is set
  63266. */
  63267. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63268. scene = _this.getScene();
  63269. if (!scene) {
  63270. return _this;
  63271. }
  63272. _this._engine = scene.getEngine();
  63273. _this.name = name;
  63274. _this.isRenderTarget = true;
  63275. _this._initialSizeParameter = size;
  63276. _this._processSizeParameter(size);
  63277. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63278. });
  63279. _this._generateMipMaps = generateMipMaps ? true : false;
  63280. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63281. // Rendering groups
  63282. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63283. if (isMulti) {
  63284. return _this;
  63285. }
  63286. _this._renderTargetOptions = {
  63287. generateMipMaps: generateMipMaps,
  63288. type: type,
  63289. samplingMode: samplingMode,
  63290. generateDepthBuffer: generateDepthBuffer,
  63291. generateStencilBuffer: generateStencilBuffer
  63292. };
  63293. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63294. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63295. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63296. }
  63297. if (isCube) {
  63298. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63299. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63300. _this._textureMatrix = BABYLON.Matrix.Identity();
  63301. }
  63302. else {
  63303. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63304. }
  63305. return _this;
  63306. }
  63307. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63308. get: function () {
  63309. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63310. },
  63311. enumerable: true,
  63312. configurable: true
  63313. });
  63314. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63315. get: function () {
  63316. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63317. },
  63318. enumerable: true,
  63319. configurable: true
  63320. });
  63321. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63322. get: function () {
  63323. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63324. },
  63325. enumerable: true,
  63326. configurable: true
  63327. });
  63328. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63329. set: function (callback) {
  63330. if (this._onAfterUnbindObserver) {
  63331. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63332. }
  63333. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63334. },
  63335. enumerable: true,
  63336. configurable: true
  63337. });
  63338. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63339. set: function (callback) {
  63340. if (this._onBeforeRenderObserver) {
  63341. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63342. }
  63343. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63344. },
  63345. enumerable: true,
  63346. configurable: true
  63347. });
  63348. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63349. set: function (callback) {
  63350. if (this._onAfterRenderObserver) {
  63351. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63352. }
  63353. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63354. },
  63355. enumerable: true,
  63356. configurable: true
  63357. });
  63358. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63359. set: function (callback) {
  63360. if (this._onClearObserver) {
  63361. this.onClearObservable.remove(this._onClearObserver);
  63362. }
  63363. this._onClearObserver = this.onClearObservable.add(callback);
  63364. },
  63365. enumerable: true,
  63366. configurable: true
  63367. });
  63368. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63369. get: function () {
  63370. return this._renderTargetOptions;
  63371. },
  63372. enumerable: true,
  63373. configurable: true
  63374. });
  63375. RenderTargetTexture.prototype._onRatioRescale = function () {
  63376. if (this._sizeRatio) {
  63377. this.resize(this._initialSizeParameter);
  63378. }
  63379. };
  63380. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63381. get: function () {
  63382. return this._boundingBoxSize;
  63383. },
  63384. /**
  63385. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63386. * When defined, the cubemap will switch to local mode
  63387. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63388. * @example https://www.babylonjs-playground.com/#RNASML
  63389. */
  63390. set: function (value) {
  63391. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63392. return;
  63393. }
  63394. this._boundingBoxSize = value;
  63395. var scene = this.getScene();
  63396. if (scene) {
  63397. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63398. }
  63399. },
  63400. enumerable: true,
  63401. configurable: true
  63402. });
  63403. /**
  63404. * Creates a depth stencil texture.
  63405. * This is only available in WebGL 2 or with the depth texture extension available.
  63406. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63407. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63408. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63409. */
  63410. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63411. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63412. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63413. if (generateStencil === void 0) { generateStencil = false; }
  63414. if (!this.getScene()) {
  63415. return;
  63416. }
  63417. var engine = this.getScene().getEngine();
  63418. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63419. bilinearFiltering: bilinearFiltering,
  63420. comparisonFunction: comparisonFunction,
  63421. generateStencil: generateStencil,
  63422. isCube: this.isCube
  63423. });
  63424. engine.setFrameBufferDepthStencilTexture(this);
  63425. };
  63426. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63427. if (size.ratio) {
  63428. this._sizeRatio = size.ratio;
  63429. this._size = {
  63430. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63431. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63432. };
  63433. }
  63434. else {
  63435. this._size = size;
  63436. }
  63437. };
  63438. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63439. get: function () {
  63440. return this._samples;
  63441. },
  63442. set: function (value) {
  63443. if (this._samples === value) {
  63444. return;
  63445. }
  63446. var scene = this.getScene();
  63447. if (!scene) {
  63448. return;
  63449. }
  63450. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63451. },
  63452. enumerable: true,
  63453. configurable: true
  63454. });
  63455. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63456. this._currentRefreshId = -1;
  63457. };
  63458. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63459. get: function () {
  63460. return this._refreshRate;
  63461. },
  63462. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63463. set: function (value) {
  63464. this._refreshRate = value;
  63465. this.resetRefreshCounter();
  63466. },
  63467. enumerable: true,
  63468. configurable: true
  63469. });
  63470. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63471. if (!this._postProcessManager) {
  63472. var scene = this.getScene();
  63473. if (!scene) {
  63474. return;
  63475. }
  63476. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63477. this._postProcesses = new Array();
  63478. }
  63479. this._postProcesses.push(postProcess);
  63480. this._postProcesses[0].autoClear = false;
  63481. };
  63482. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63483. if (!this._postProcesses) {
  63484. return;
  63485. }
  63486. if (dispose) {
  63487. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63488. var postProcess = _a[_i];
  63489. postProcess.dispose();
  63490. }
  63491. }
  63492. this._postProcesses = [];
  63493. };
  63494. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63495. if (!this._postProcesses) {
  63496. return;
  63497. }
  63498. var index = this._postProcesses.indexOf(postProcess);
  63499. if (index === -1) {
  63500. return;
  63501. }
  63502. this._postProcesses.splice(index, 1);
  63503. if (this._postProcesses.length > 0) {
  63504. this._postProcesses[0].autoClear = false;
  63505. }
  63506. };
  63507. RenderTargetTexture.prototype._shouldRender = function () {
  63508. if (this._currentRefreshId === -1) { // At least render once
  63509. this._currentRefreshId = 1;
  63510. return true;
  63511. }
  63512. if (this.refreshRate === this._currentRefreshId) {
  63513. this._currentRefreshId = 1;
  63514. return true;
  63515. }
  63516. this._currentRefreshId++;
  63517. return false;
  63518. };
  63519. RenderTargetTexture.prototype.getRenderSize = function () {
  63520. if (this._size.width) {
  63521. return this._size.width;
  63522. }
  63523. return this._size;
  63524. };
  63525. RenderTargetTexture.prototype.getRenderWidth = function () {
  63526. if (this._size.width) {
  63527. return this._size.width;
  63528. }
  63529. return this._size;
  63530. };
  63531. RenderTargetTexture.prototype.getRenderHeight = function () {
  63532. if (this._size.width) {
  63533. return this._size.height;
  63534. }
  63535. return this._size;
  63536. };
  63537. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63538. get: function () {
  63539. return true;
  63540. },
  63541. enumerable: true,
  63542. configurable: true
  63543. });
  63544. RenderTargetTexture.prototype.scale = function (ratio) {
  63545. var newSize = this.getRenderSize() * ratio;
  63546. this.resize(newSize);
  63547. };
  63548. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63549. if (this.isCube) {
  63550. return this._textureMatrix;
  63551. }
  63552. return _super.prototype.getReflectionTextureMatrix.call(this);
  63553. };
  63554. RenderTargetTexture.prototype.resize = function (size) {
  63555. this.releaseInternalTexture();
  63556. var scene = this.getScene();
  63557. if (!scene) {
  63558. return;
  63559. }
  63560. this._processSizeParameter(size);
  63561. if (this.isCube) {
  63562. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63563. }
  63564. else {
  63565. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63566. }
  63567. };
  63568. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63569. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63570. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63571. var scene = this.getScene();
  63572. if (!scene) {
  63573. return;
  63574. }
  63575. var engine = scene.getEngine();
  63576. if (this.useCameraPostProcesses !== undefined) {
  63577. useCameraPostProcess = this.useCameraPostProcesses;
  63578. }
  63579. if (this._waitingRenderList) {
  63580. this.renderList = [];
  63581. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63582. var id = this._waitingRenderList[index];
  63583. var mesh_1 = scene.getMeshByID(id);
  63584. if (mesh_1) {
  63585. this.renderList.push(mesh_1);
  63586. }
  63587. }
  63588. delete this._waitingRenderList;
  63589. }
  63590. // Is predicate defined?
  63591. if (this.renderListPredicate) {
  63592. if (this.renderList) {
  63593. this.renderList.splice(0); // Clear previous renderList
  63594. }
  63595. else {
  63596. this.renderList = [];
  63597. }
  63598. var scene = this.getScene();
  63599. if (!scene) {
  63600. return;
  63601. }
  63602. var sceneMeshes = scene.meshes;
  63603. for (var index = 0; index < sceneMeshes.length; index++) {
  63604. var mesh = sceneMeshes[index];
  63605. if (this.renderListPredicate(mesh)) {
  63606. this.renderList.push(mesh);
  63607. }
  63608. }
  63609. }
  63610. this.onBeforeBindObservable.notifyObservers(this);
  63611. // Set custom projection.
  63612. // Needs to be before binding to prevent changing the aspect ratio.
  63613. var camera;
  63614. if (this.activeCamera) {
  63615. camera = this.activeCamera;
  63616. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63617. if (this.activeCamera !== scene.activeCamera) {
  63618. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63619. }
  63620. }
  63621. else {
  63622. camera = scene.activeCamera;
  63623. if (camera) {
  63624. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63625. }
  63626. }
  63627. // Prepare renderingManager
  63628. this._renderingManager.reset();
  63629. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63630. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63631. var sceneRenderId = scene.getRenderId();
  63632. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63633. var mesh = currentRenderList[meshIndex];
  63634. if (mesh) {
  63635. if (!mesh.isReady(this.refreshRate === 0)) {
  63636. this.resetRefreshCounter();
  63637. continue;
  63638. }
  63639. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63640. var isMasked = void 0;
  63641. if (!this.renderList && camera) {
  63642. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63643. }
  63644. else {
  63645. isMasked = false;
  63646. }
  63647. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63648. mesh._activate(sceneRenderId);
  63649. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63650. var subMesh = mesh.subMeshes[subIndex];
  63651. scene._activeIndices.addCount(subMesh.indexCount, false);
  63652. this._renderingManager.dispatch(subMesh, mesh);
  63653. }
  63654. }
  63655. }
  63656. }
  63657. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63658. var particleSystem = scene.particleSystems[particleIndex];
  63659. var emitter = particleSystem.emitter;
  63660. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63661. continue;
  63662. }
  63663. if (currentRenderList.indexOf(emitter) >= 0) {
  63664. this._renderingManager.dispatchParticles(particleSystem);
  63665. }
  63666. }
  63667. if (this.isCube) {
  63668. for (var face = 0; face < 6; face++) {
  63669. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63670. scene.incrementRenderId();
  63671. scene.resetCachedMaterial();
  63672. }
  63673. }
  63674. else {
  63675. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63676. }
  63677. this.onAfterUnbindObservable.notifyObservers(this);
  63678. if (scene.activeCamera) {
  63679. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63680. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63681. }
  63682. engine.setViewport(scene.activeCamera.viewport);
  63683. }
  63684. scene.resetCachedMaterial();
  63685. };
  63686. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63687. var minimum = 128;
  63688. var x = renderDimension * scale;
  63689. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63690. // Ensure we don't exceed the render dimension (while staying POT)
  63691. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63692. };
  63693. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63694. var _this = this;
  63695. if (!this._texture) {
  63696. return;
  63697. }
  63698. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63699. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63700. });
  63701. };
  63702. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63703. var scene = this.getScene();
  63704. if (!scene) {
  63705. return;
  63706. }
  63707. var engine = scene.getEngine();
  63708. if (!this._texture) {
  63709. return;
  63710. }
  63711. // Bind
  63712. if (this._postProcessManager) {
  63713. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63714. }
  63715. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63716. if (this._texture) {
  63717. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63718. }
  63719. }
  63720. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63721. // Clear
  63722. if (this.onClearObservable.hasObservers()) {
  63723. this.onClearObservable.notifyObservers(engine);
  63724. }
  63725. else {
  63726. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63727. }
  63728. if (!this._doNotChangeAspectRatio) {
  63729. scene.updateTransformMatrix(true);
  63730. }
  63731. // Render
  63732. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63733. if (this._postProcessManager) {
  63734. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63735. }
  63736. else if (useCameraPostProcess) {
  63737. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63738. }
  63739. if (!this._doNotChangeAspectRatio) {
  63740. scene.updateTransformMatrix(true);
  63741. }
  63742. // Dump ?
  63743. if (dumpForDebug) {
  63744. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63745. }
  63746. // Unbind
  63747. if (!this.isCube || faceIndex === 5) {
  63748. if (this.isCube) {
  63749. if (faceIndex === 5) {
  63750. engine.generateMipMapsForCubemap(this._texture);
  63751. }
  63752. }
  63753. this.unbindFrameBuffer(engine, faceIndex);
  63754. }
  63755. else {
  63756. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63757. }
  63758. };
  63759. /**
  63760. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63761. * This allowed control for front to back rendering or reversly depending of the special needs.
  63762. *
  63763. * @param renderingGroupId The rendering group id corresponding to its index
  63764. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63765. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63766. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63767. */
  63768. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63769. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63770. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63771. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63772. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63773. };
  63774. /**
  63775. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63776. *
  63777. * @param renderingGroupId The rendering group id corresponding to its index
  63778. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63779. */
  63780. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63781. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63782. };
  63783. RenderTargetTexture.prototype.clone = function () {
  63784. var textureSize = this.getSize();
  63785. 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);
  63786. // Base texture
  63787. newTexture.hasAlpha = this.hasAlpha;
  63788. newTexture.level = this.level;
  63789. // RenderTarget Texture
  63790. newTexture.coordinatesMode = this.coordinatesMode;
  63791. if (this.renderList) {
  63792. newTexture.renderList = this.renderList.slice(0);
  63793. }
  63794. return newTexture;
  63795. };
  63796. RenderTargetTexture.prototype.serialize = function () {
  63797. if (!this.name) {
  63798. return null;
  63799. }
  63800. var serializationObject = _super.prototype.serialize.call(this);
  63801. serializationObject.renderTargetSize = this.getRenderSize();
  63802. serializationObject.renderList = [];
  63803. if (this.renderList) {
  63804. for (var index = 0; index < this.renderList.length; index++) {
  63805. serializationObject.renderList.push(this.renderList[index].id);
  63806. }
  63807. }
  63808. return serializationObject;
  63809. };
  63810. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63811. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63812. var objBuffer = this.getInternalTexture();
  63813. var scene = this.getScene();
  63814. if (objBuffer && scene) {
  63815. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63816. }
  63817. };
  63818. RenderTargetTexture.prototype.dispose = function () {
  63819. if (this._postProcessManager) {
  63820. this._postProcessManager.dispose();
  63821. this._postProcessManager = null;
  63822. }
  63823. this.clearPostProcesses(true);
  63824. if (this._resizeObserver) {
  63825. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63826. this._resizeObserver = null;
  63827. }
  63828. this.renderList = null;
  63829. // Remove from custom render targets
  63830. var scene = this.getScene();
  63831. if (!scene) {
  63832. return;
  63833. }
  63834. var index = scene.customRenderTargets.indexOf(this);
  63835. if (index >= 0) {
  63836. scene.customRenderTargets.splice(index, 1);
  63837. }
  63838. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63839. var camera = _a[_i];
  63840. index = camera.customRenderTargets.indexOf(this);
  63841. if (index >= 0) {
  63842. camera.customRenderTargets.splice(index, 1);
  63843. }
  63844. }
  63845. _super.prototype.dispose.call(this);
  63846. };
  63847. RenderTargetTexture.prototype._rebuild = function () {
  63848. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63849. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63850. }
  63851. if (this._postProcessManager) {
  63852. this._postProcessManager._rebuild();
  63853. }
  63854. };
  63855. /**
  63856. * Clear the info related to rendering groups preventing retention point in material dispose.
  63857. */
  63858. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63859. if (this._renderingManager) {
  63860. this._renderingManager.freeRenderingGroups();
  63861. }
  63862. };
  63863. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63864. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63865. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63866. return RenderTargetTexture;
  63867. }(BABYLON.Texture));
  63868. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63869. })(BABYLON || (BABYLON = {}));
  63870. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63871. var BABYLON;
  63872. (function (BABYLON) {
  63873. ;
  63874. var MultiRenderTarget = /** @class */ (function (_super) {
  63875. __extends(MultiRenderTarget, _super);
  63876. function MultiRenderTarget(name, size, count, scene, options) {
  63877. var _this = this;
  63878. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63879. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63880. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63881. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63882. _this._engine = scene.getEngine();
  63883. if (!_this.isSupported) {
  63884. _this.dispose();
  63885. return;
  63886. }
  63887. var types = [];
  63888. var samplingModes = [];
  63889. for (var i = 0; i < count; i++) {
  63890. if (options && options.types && options.types[i] !== undefined) {
  63891. types.push(options.types[i]);
  63892. }
  63893. else {
  63894. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63895. }
  63896. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63897. samplingModes.push(options.samplingModes[i]);
  63898. }
  63899. else {
  63900. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63901. }
  63902. }
  63903. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63904. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63905. _this._size = size;
  63906. _this._multiRenderTargetOptions = {
  63907. samplingModes: samplingModes,
  63908. generateMipMaps: generateMipMaps,
  63909. generateDepthBuffer: generateDepthBuffer,
  63910. generateStencilBuffer: generateStencilBuffer,
  63911. generateDepthTexture: generateDepthTexture,
  63912. types: types,
  63913. textureCount: count
  63914. };
  63915. _this._createInternalTextures();
  63916. _this._createTextures();
  63917. return _this;
  63918. }
  63919. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63920. get: function () {
  63921. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63922. },
  63923. enumerable: true,
  63924. configurable: true
  63925. });
  63926. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63927. get: function () {
  63928. return this._textures;
  63929. },
  63930. enumerable: true,
  63931. configurable: true
  63932. });
  63933. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63934. get: function () {
  63935. return this._textures[this._textures.length - 1];
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63941. set: function (wrap) {
  63942. if (this._textures) {
  63943. for (var i = 0; i < this._textures.length; i++) {
  63944. this._textures[i].wrapU = wrap;
  63945. }
  63946. }
  63947. },
  63948. enumerable: true,
  63949. configurable: true
  63950. });
  63951. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63952. set: function (wrap) {
  63953. if (this._textures) {
  63954. for (var i = 0; i < this._textures.length; i++) {
  63955. this._textures[i].wrapV = wrap;
  63956. }
  63957. }
  63958. },
  63959. enumerable: true,
  63960. configurable: true
  63961. });
  63962. MultiRenderTarget.prototype._rebuild = function () {
  63963. this.releaseInternalTextures();
  63964. this._createInternalTextures();
  63965. for (var i = 0; i < this._internalTextures.length; i++) {
  63966. var texture = this._textures[i];
  63967. texture._texture = this._internalTextures[i];
  63968. }
  63969. // Keeps references to frame buffer and stencil/depth buffer
  63970. this._texture = this._internalTextures[0];
  63971. };
  63972. MultiRenderTarget.prototype._createInternalTextures = function () {
  63973. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63974. };
  63975. MultiRenderTarget.prototype._createTextures = function () {
  63976. this._textures = [];
  63977. for (var i = 0; i < this._internalTextures.length; i++) {
  63978. var texture = new BABYLON.Texture(null, this.getScene());
  63979. texture._texture = this._internalTextures[i];
  63980. this._textures.push(texture);
  63981. }
  63982. // Keeps references to frame buffer and stencil/depth buffer
  63983. this._texture = this._internalTextures[0];
  63984. };
  63985. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63986. get: function () {
  63987. return this._samples;
  63988. },
  63989. set: function (value) {
  63990. if (this._samples === value) {
  63991. return;
  63992. }
  63993. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63994. },
  63995. enumerable: true,
  63996. configurable: true
  63997. });
  63998. MultiRenderTarget.prototype.resize = function (size) {
  63999. this.releaseInternalTextures();
  64000. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64001. this._createInternalTextures();
  64002. };
  64003. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64004. var _this = this;
  64005. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64006. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64007. });
  64008. };
  64009. MultiRenderTarget.prototype.dispose = function () {
  64010. this.releaseInternalTextures();
  64011. _super.prototype.dispose.call(this);
  64012. };
  64013. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64014. if (!this._internalTextures) {
  64015. return;
  64016. }
  64017. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64018. if (this._internalTextures[i] !== undefined) {
  64019. this._internalTextures[i].dispose();
  64020. this._internalTextures.splice(i, 1);
  64021. }
  64022. }
  64023. };
  64024. return MultiRenderTarget;
  64025. }(BABYLON.RenderTargetTexture));
  64026. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64027. })(BABYLON || (BABYLON = {}));
  64028. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64029. var BABYLON;
  64030. (function (BABYLON) {
  64031. var MirrorTexture = /** @class */ (function (_super) {
  64032. __extends(MirrorTexture, _super);
  64033. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64034. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64036. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64037. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64038. _this.scene = scene;
  64039. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64040. _this._transformMatrix = BABYLON.Matrix.Zero();
  64041. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64042. _this._adaptiveBlurKernel = 0;
  64043. _this._blurKernelX = 0;
  64044. _this._blurKernelY = 0;
  64045. _this._blurRatio = 1.0;
  64046. _this.ignoreCameraViewport = true;
  64047. _this._updateGammaSpace();
  64048. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64049. _this._updateGammaSpace;
  64050. });
  64051. _this.onBeforeRenderObservable.add(function () {
  64052. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64053. _this._savedViewMatrix = scene.getViewMatrix();
  64054. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64055. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64056. scene.clipPlane = _this.mirrorPlane;
  64057. scene.getEngine().cullBackFaces = false;
  64058. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64059. });
  64060. _this.onAfterRenderObservable.add(function () {
  64061. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64062. scene.getEngine().cullBackFaces = true;
  64063. scene._mirroredCameraPosition = null;
  64064. delete scene.clipPlane;
  64065. });
  64066. return _this;
  64067. }
  64068. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64069. get: function () {
  64070. return this._blurRatio;
  64071. },
  64072. set: function (value) {
  64073. if (this._blurRatio === value) {
  64074. return;
  64075. }
  64076. this._blurRatio = value;
  64077. this._preparePostProcesses();
  64078. },
  64079. enumerable: true,
  64080. configurable: true
  64081. });
  64082. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64083. set: function (value) {
  64084. this._adaptiveBlurKernel = value;
  64085. this._autoComputeBlurKernel();
  64086. },
  64087. enumerable: true,
  64088. configurable: true
  64089. });
  64090. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64091. set: function (value) {
  64092. this.blurKernelX = value;
  64093. this.blurKernelY = value;
  64094. },
  64095. enumerable: true,
  64096. configurable: true
  64097. });
  64098. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64099. get: function () {
  64100. return this._blurKernelX;
  64101. },
  64102. set: function (value) {
  64103. if (this._blurKernelX === value) {
  64104. return;
  64105. }
  64106. this._blurKernelX = value;
  64107. this._preparePostProcesses();
  64108. },
  64109. enumerable: true,
  64110. configurable: true
  64111. });
  64112. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64113. get: function () {
  64114. return this._blurKernelY;
  64115. },
  64116. set: function (value) {
  64117. if (this._blurKernelY === value) {
  64118. return;
  64119. }
  64120. this._blurKernelY = value;
  64121. this._preparePostProcesses();
  64122. },
  64123. enumerable: true,
  64124. configurable: true
  64125. });
  64126. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64127. var engine = this.getScene().getEngine();
  64128. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64129. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64130. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64131. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64132. };
  64133. MirrorTexture.prototype._onRatioRescale = function () {
  64134. if (this._sizeRatio) {
  64135. this.resize(this._initialSizeParameter);
  64136. if (!this._adaptiveBlurKernel) {
  64137. this._preparePostProcesses();
  64138. }
  64139. }
  64140. if (this._adaptiveBlurKernel) {
  64141. this._autoComputeBlurKernel();
  64142. }
  64143. };
  64144. MirrorTexture.prototype._updateGammaSpace = function () {
  64145. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64146. };
  64147. MirrorTexture.prototype._preparePostProcesses = function () {
  64148. this.clearPostProcesses(true);
  64149. if (this._blurKernelX && this._blurKernelY) {
  64150. var engine = this.getScene().getEngine();
  64151. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64152. 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);
  64153. this._blurX.autoClear = false;
  64154. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64155. this._blurX.inputTexture = this._texture;
  64156. }
  64157. else {
  64158. this._blurX.alwaysForcePOT = true;
  64159. }
  64160. 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);
  64161. this._blurY.autoClear = false;
  64162. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64163. this.addPostProcess(this._blurX);
  64164. this.addPostProcess(this._blurY);
  64165. }
  64166. else {
  64167. if (this._blurY) {
  64168. this.removePostProcess(this._blurY);
  64169. this._blurY.dispose();
  64170. this._blurY = null;
  64171. }
  64172. if (this._blurX) {
  64173. this.removePostProcess(this._blurX);
  64174. this._blurX.dispose();
  64175. this._blurX = null;
  64176. }
  64177. }
  64178. };
  64179. MirrorTexture.prototype.clone = function () {
  64180. var scene = this.getScene();
  64181. if (!scene) {
  64182. return this;
  64183. }
  64184. var textureSize = this.getSize();
  64185. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64186. // Base texture
  64187. newTexture.hasAlpha = this.hasAlpha;
  64188. newTexture.level = this.level;
  64189. // Mirror Texture
  64190. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64191. if (this.renderList) {
  64192. newTexture.renderList = this.renderList.slice(0);
  64193. }
  64194. return newTexture;
  64195. };
  64196. MirrorTexture.prototype.serialize = function () {
  64197. if (!this.name) {
  64198. return null;
  64199. }
  64200. var serializationObject = _super.prototype.serialize.call(this);
  64201. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64202. return serializationObject;
  64203. };
  64204. MirrorTexture.prototype.dispose = function () {
  64205. _super.prototype.dispose.call(this);
  64206. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64207. };
  64208. return MirrorTexture;
  64209. }(BABYLON.RenderTargetTexture));
  64210. BABYLON.MirrorTexture = MirrorTexture;
  64211. })(BABYLON || (BABYLON = {}));
  64212. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64213. var BABYLON;
  64214. (function (BABYLON) {
  64215. /**
  64216. * Creates a refraction texture used by refraction channel of the standard material.
  64217. * @param name the texture name
  64218. * @param size size of the underlying texture
  64219. * @param scene root scene
  64220. */
  64221. var RefractionTexture = /** @class */ (function (_super) {
  64222. __extends(RefractionTexture, _super);
  64223. function RefractionTexture(name, size, scene, generateMipMaps) {
  64224. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64225. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64226. _this.depth = 2.0;
  64227. _this.onBeforeRenderObservable.add(function () {
  64228. scene.clipPlane = _this.refractionPlane;
  64229. });
  64230. _this.onAfterRenderObservable.add(function () {
  64231. delete scene.clipPlane;
  64232. });
  64233. return _this;
  64234. }
  64235. RefractionTexture.prototype.clone = function () {
  64236. var scene = this.getScene();
  64237. if (!scene) {
  64238. return this;
  64239. }
  64240. var textureSize = this.getSize();
  64241. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64242. // Base texture
  64243. newTexture.hasAlpha = this.hasAlpha;
  64244. newTexture.level = this.level;
  64245. // Refraction Texture
  64246. newTexture.refractionPlane = this.refractionPlane.clone();
  64247. if (this.renderList) {
  64248. newTexture.renderList = this.renderList.slice(0);
  64249. }
  64250. newTexture.depth = this.depth;
  64251. return newTexture;
  64252. };
  64253. RefractionTexture.prototype.serialize = function () {
  64254. if (!this.name) {
  64255. return null;
  64256. }
  64257. var serializationObject = _super.prototype.serialize.call(this);
  64258. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64259. serializationObject.depth = this.depth;
  64260. return serializationObject;
  64261. };
  64262. return RefractionTexture;
  64263. }(BABYLON.RenderTargetTexture));
  64264. BABYLON.RefractionTexture = RefractionTexture;
  64265. })(BABYLON || (BABYLON = {}));
  64266. //# sourceMappingURL=babylon.refractionTexture.js.map
  64267. var BABYLON;
  64268. (function (BABYLON) {
  64269. /**
  64270. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64271. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64272. */
  64273. var DynamicTexture = /** @class */ (function (_super) {
  64274. __extends(DynamicTexture, _super);
  64275. /**
  64276. * Creates a {BABYLON.DynamicTexture}
  64277. * @param name defines the name of the texture
  64278. * @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
  64279. * @param scene defines the scene where you want the texture
  64280. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64281. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64282. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64283. */
  64284. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64285. if (scene === void 0) { scene = null; }
  64286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64287. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64288. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64289. _this.name = name;
  64290. _this._engine = _this.getScene().getEngine();
  64291. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64292. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64293. _this._generateMipMaps = generateMipMaps;
  64294. if (options.getContext) {
  64295. _this._canvas = options;
  64296. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64297. }
  64298. else {
  64299. _this._canvas = document.createElement("canvas");
  64300. if (options.width || options.width === 0) {
  64301. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64302. }
  64303. else {
  64304. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64305. }
  64306. }
  64307. var textureSize = _this.getSize();
  64308. _this._canvas.width = textureSize.width;
  64309. _this._canvas.height = textureSize.height;
  64310. _this._context = _this._canvas.getContext("2d");
  64311. return _this;
  64312. }
  64313. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64314. /**
  64315. * Gets the current state of canRescale
  64316. */
  64317. get: function () {
  64318. return true;
  64319. },
  64320. enumerable: true,
  64321. configurable: true
  64322. });
  64323. DynamicTexture.prototype._recreate = function (textureSize) {
  64324. this._canvas.width = textureSize.width;
  64325. this._canvas.height = textureSize.height;
  64326. this.releaseInternalTexture();
  64327. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64328. };
  64329. /**
  64330. * Scales the texture
  64331. * @param ratio the scale factor to apply to both width and height
  64332. */
  64333. DynamicTexture.prototype.scale = function (ratio) {
  64334. var textureSize = this.getSize();
  64335. textureSize.width *= ratio;
  64336. textureSize.height *= ratio;
  64337. this._recreate(textureSize);
  64338. };
  64339. /**
  64340. * Resizes the texture
  64341. * @param width the new width
  64342. * @param height the new height
  64343. */
  64344. DynamicTexture.prototype.scaleTo = function (width, height) {
  64345. var textureSize = this.getSize();
  64346. textureSize.width = width;
  64347. textureSize.height = height;
  64348. this._recreate(textureSize);
  64349. };
  64350. /**
  64351. * Gets the context of the canvas used by the texture
  64352. * @returns the canvas context of the dynamic texture
  64353. */
  64354. DynamicTexture.prototype.getContext = function () {
  64355. return this._context;
  64356. };
  64357. /**
  64358. * Clears the texture
  64359. */
  64360. DynamicTexture.prototype.clear = function () {
  64361. var size = this.getSize();
  64362. this._context.fillRect(0, 0, size.width, size.height);
  64363. };
  64364. /**
  64365. * Updates the texture
  64366. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64367. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64368. */
  64369. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64370. if (premulAlpha === void 0) { premulAlpha = false; }
  64371. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64372. };
  64373. /**
  64374. * Draws text onto the texture
  64375. * @param text defines the text to be drawn
  64376. * @param x defines the placement of the text from the left
  64377. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64378. * @param font defines the font to be used with font-style, font-size, font-name
  64379. * @param color defines the color used for the text
  64380. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64381. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64382. * @param update defines whether texture is immediately update (default is true)
  64383. */
  64384. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64385. if (update === void 0) { update = true; }
  64386. var size = this.getSize();
  64387. if (clearColor) {
  64388. this._context.fillStyle = clearColor;
  64389. this._context.fillRect(0, 0, size.width, size.height);
  64390. }
  64391. this._context.font = font;
  64392. if (x === null || x === undefined) {
  64393. var textSize = this._context.measureText(text);
  64394. x = (size.width - textSize.width) / 2;
  64395. }
  64396. if (y === null || y === undefined) {
  64397. var fontSize = parseInt((font.replace(/\D/g, '')));
  64398. y = (size.height / 2) + (fontSize / 3.65);
  64399. }
  64400. this._context.fillStyle = color;
  64401. this._context.fillText(text, x, y);
  64402. if (update) {
  64403. this.update(invertY);
  64404. }
  64405. };
  64406. /**
  64407. * Clones the texture
  64408. * @returns the clone of the texture.
  64409. */
  64410. DynamicTexture.prototype.clone = function () {
  64411. var scene = this.getScene();
  64412. if (!scene) {
  64413. return this;
  64414. }
  64415. var textureSize = this.getSize();
  64416. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64417. // Base texture
  64418. newTexture.hasAlpha = this.hasAlpha;
  64419. newTexture.level = this.level;
  64420. // Dynamic Texture
  64421. newTexture.wrapU = this.wrapU;
  64422. newTexture.wrapV = this.wrapV;
  64423. return newTexture;
  64424. };
  64425. /** @hidden */
  64426. DynamicTexture.prototype._rebuild = function () {
  64427. this.update();
  64428. };
  64429. return DynamicTexture;
  64430. }(BABYLON.Texture));
  64431. BABYLON.DynamicTexture = DynamicTexture;
  64432. })(BABYLON || (BABYLON = {}));
  64433. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64434. var BABYLON;
  64435. (function (BABYLON) {
  64436. var VideoTexture = /** @class */ (function (_super) {
  64437. __extends(VideoTexture, _super);
  64438. /**
  64439. * Creates a video texture.
  64440. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64441. * @param {string | null} name optional name, will detect from video source, if not defined
  64442. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64443. * @param {BABYLON.Scene} scene is obviously the current scene.
  64444. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64445. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64446. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64447. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64448. */
  64449. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64450. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64451. if (invertY === void 0) { invertY = false; }
  64452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64453. if (settings === void 0) { settings = {
  64454. autoPlay: true,
  64455. loop: true,
  64456. autoUpdateTexture: true,
  64457. }; }
  64458. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64459. _this._onUserActionRequestedObservable = null;
  64460. _this._stillImageCaptured = false;
  64461. _this._createInternalTexture = function () {
  64462. if (_this._texture != null) {
  64463. return;
  64464. }
  64465. if (!_this._engine.needPOTTextures ||
  64466. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64467. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64468. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64469. }
  64470. else {
  64471. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64472. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64473. _this._generateMipMaps = false;
  64474. }
  64475. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64476. if (!_this.video.autoplay) {
  64477. var oldHandler_1 = _this.video.onplaying;
  64478. var error_1 = false;
  64479. _this.video.onplaying = function () {
  64480. _this.video.onplaying = oldHandler_1;
  64481. _this._texture.isReady = true;
  64482. _this._updateInternalTexture();
  64483. if (!error_1) {
  64484. _this.video.pause();
  64485. }
  64486. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64487. _this.onLoadObservable.notifyObservers(_this);
  64488. }
  64489. };
  64490. var playing = _this.video.play();
  64491. if (playing) {
  64492. playing.then(function () {
  64493. // Everything is good.
  64494. })
  64495. .catch(function () {
  64496. error_1 = true;
  64497. // On Chrome for instance, new policies might prevent playing without user interaction.
  64498. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64499. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64500. }
  64501. });
  64502. }
  64503. else {
  64504. _this.video.onplaying = oldHandler_1;
  64505. _this._texture.isReady = true;
  64506. _this._updateInternalTexture();
  64507. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64508. _this.onLoadObservable.notifyObservers(_this);
  64509. }
  64510. }
  64511. }
  64512. else {
  64513. _this._texture.isReady = true;
  64514. _this._updateInternalTexture();
  64515. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64516. _this.onLoadObservable.notifyObservers(_this);
  64517. }
  64518. }
  64519. };
  64520. _this.reset = function () {
  64521. if (_this._texture == null) {
  64522. return;
  64523. }
  64524. _this._texture.dispose();
  64525. _this._texture = null;
  64526. };
  64527. _this._updateInternalTexture = function (e) {
  64528. if (_this._texture == null || !_this._texture.isReady) {
  64529. return;
  64530. }
  64531. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64532. return;
  64533. }
  64534. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64535. };
  64536. _this._engine = _this.getScene().getEngine();
  64537. _this._generateMipMaps = generateMipMaps;
  64538. _this._samplingMode = samplingMode;
  64539. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64540. _this.name = name || _this._getName(src);
  64541. _this.video = _this._getVideo(src);
  64542. if (settings.poster) {
  64543. _this.video.poster = settings.poster;
  64544. }
  64545. if (settings.autoPlay !== undefined) {
  64546. _this.video.autoplay = settings.autoPlay;
  64547. }
  64548. if (settings.loop !== undefined) {
  64549. _this.video.loop = settings.loop;
  64550. }
  64551. _this.video.setAttribute("playsinline", "");
  64552. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64553. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64554. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64555. _this.video.addEventListener("emptied", _this.reset);
  64556. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64557. _this._createInternalTexture();
  64558. }
  64559. return _this;
  64560. }
  64561. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64562. get: function () {
  64563. if (!this._onUserActionRequestedObservable) {
  64564. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64565. }
  64566. return this._onUserActionRequestedObservable;
  64567. },
  64568. enumerable: true,
  64569. configurable: true
  64570. });
  64571. VideoTexture.prototype._getName = function (src) {
  64572. if (src instanceof HTMLVideoElement) {
  64573. return src.currentSrc;
  64574. }
  64575. if (typeof src === "object") {
  64576. return src.toString();
  64577. }
  64578. return src;
  64579. };
  64580. ;
  64581. VideoTexture.prototype._getVideo = function (src) {
  64582. if (src instanceof HTMLVideoElement) {
  64583. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64584. return src;
  64585. }
  64586. var video = document.createElement("video");
  64587. if (typeof src === "string") {
  64588. BABYLON.Tools.SetCorsBehavior(src, video);
  64589. video.src = src;
  64590. }
  64591. else {
  64592. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64593. src.forEach(function (url) {
  64594. var source = document.createElement("source");
  64595. source.src = url;
  64596. video.appendChild(source);
  64597. });
  64598. }
  64599. return video;
  64600. };
  64601. ;
  64602. /**
  64603. * Internal method to initiate `update`.
  64604. */
  64605. VideoTexture.prototype._rebuild = function () {
  64606. this.update();
  64607. };
  64608. /**
  64609. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64610. */
  64611. VideoTexture.prototype.update = function () {
  64612. if (!this.autoUpdateTexture) {
  64613. // Expecting user to call `updateTexture` manually
  64614. return;
  64615. }
  64616. this.updateTexture(true);
  64617. };
  64618. /**
  64619. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64620. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64621. */
  64622. VideoTexture.prototype.updateTexture = function (isVisible) {
  64623. if (!isVisible) {
  64624. return;
  64625. }
  64626. if (this.video.paused && this._stillImageCaptured) {
  64627. return;
  64628. }
  64629. this._stillImageCaptured = true;
  64630. this._updateInternalTexture();
  64631. };
  64632. /**
  64633. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64634. * @param url New url.
  64635. */
  64636. VideoTexture.prototype.updateURL = function (url) {
  64637. this.video.src = url;
  64638. };
  64639. VideoTexture.prototype.dispose = function () {
  64640. _super.prototype.dispose.call(this);
  64641. if (this._onUserActionRequestedObservable) {
  64642. this._onUserActionRequestedObservable.clear();
  64643. this._onUserActionRequestedObservable = null;
  64644. }
  64645. this.video.removeEventListener("canplay", this._createInternalTexture);
  64646. this.video.removeEventListener("paused", this._updateInternalTexture);
  64647. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64648. this.video.removeEventListener("emptied", this.reset);
  64649. this.video.pause();
  64650. };
  64651. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64652. var video = document.createElement("video");
  64653. video.setAttribute('autoplay', '');
  64654. video.setAttribute('muted', '');
  64655. video.setAttribute('playsinline', '');
  64656. var constraintsDeviceId;
  64657. if (constraints && constraints.deviceId) {
  64658. constraintsDeviceId = {
  64659. exact: constraints.deviceId,
  64660. };
  64661. }
  64662. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64663. if (navigator.mediaDevices) {
  64664. navigator.mediaDevices.getUserMedia({ video: constraints })
  64665. .then(function (stream) {
  64666. if (video.mozSrcObject !== undefined) {
  64667. // hack for Firefox < 19
  64668. video.mozSrcObject = stream;
  64669. }
  64670. else {
  64671. video.srcObject = stream;
  64672. }
  64673. var onPlaying = function () {
  64674. if (onReady) {
  64675. onReady(new VideoTexture("video", video, scene, true, true));
  64676. }
  64677. video.removeEventListener("playing", onPlaying);
  64678. };
  64679. video.addEventListener("playing", onPlaying);
  64680. video.play();
  64681. })
  64682. .catch(function (err) {
  64683. BABYLON.Tools.Error(err.name);
  64684. });
  64685. }
  64686. else {
  64687. navigator.getUserMedia =
  64688. navigator.getUserMedia ||
  64689. navigator.webkitGetUserMedia ||
  64690. navigator.mozGetUserMedia ||
  64691. navigator.msGetUserMedia;
  64692. if (navigator.getUserMedia) {
  64693. navigator.getUserMedia({
  64694. video: {
  64695. deviceId: constraintsDeviceId,
  64696. width: {
  64697. min: (constraints && constraints.minWidth) || 256,
  64698. max: (constraints && constraints.maxWidth) || 640,
  64699. },
  64700. height: {
  64701. min: (constraints && constraints.minHeight) || 256,
  64702. max: (constraints && constraints.maxHeight) || 480,
  64703. },
  64704. },
  64705. }, function (stream) {
  64706. if (video.mozSrcObject !== undefined) {
  64707. // hack for Firefox < 19
  64708. video.mozSrcObject = stream;
  64709. }
  64710. else {
  64711. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64712. }
  64713. video.play();
  64714. if (onReady) {
  64715. onReady(new VideoTexture("video", video, scene, true, true));
  64716. }
  64717. }, function (e) {
  64718. BABYLON.Tools.Error(e.name);
  64719. });
  64720. }
  64721. }
  64722. };
  64723. return VideoTexture;
  64724. }(BABYLON.Texture));
  64725. BABYLON.VideoTexture = VideoTexture;
  64726. })(BABYLON || (BABYLON = {}));
  64727. //# sourceMappingURL=babylon.videoTexture.js.map
  64728. var BABYLON;
  64729. (function (BABYLON) {
  64730. var RawTexture = /** @class */ (function (_super) {
  64731. __extends(RawTexture, _super);
  64732. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64734. if (invertY === void 0) { invertY = false; }
  64735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64736. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64737. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64738. _this.format = format;
  64739. _this._engine = scene.getEngine();
  64740. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64743. return _this;
  64744. }
  64745. RawTexture.prototype.update = function (data) {
  64746. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64747. };
  64748. // Statics
  64749. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64750. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64751. if (invertY === void 0) { invertY = false; }
  64752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64753. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64754. };
  64755. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64757. if (invertY === void 0) { invertY = false; }
  64758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64759. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64760. };
  64761. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64763. if (invertY === void 0) { invertY = false; }
  64764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64765. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64766. };
  64767. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64769. if (invertY === void 0) { invertY = false; }
  64770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64771. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64772. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64773. };
  64774. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64776. if (invertY === void 0) { invertY = false; }
  64777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64778. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64779. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64780. };
  64781. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64782. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64783. if (invertY === void 0) { invertY = false; }
  64784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64785. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64786. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64787. };
  64788. return RawTexture;
  64789. }(BABYLON.Texture));
  64790. BABYLON.RawTexture = RawTexture;
  64791. })(BABYLON || (BABYLON = {}));
  64792. //# sourceMappingURL=babylon.rawTexture.js.map
  64793. var BABYLON;
  64794. (function (BABYLON) {
  64795. /**
  64796. * Class used to store 3D textures containing user data
  64797. */
  64798. var RawTexture3D = /** @class */ (function (_super) {
  64799. __extends(RawTexture3D, _super);
  64800. /**
  64801. * Create a new RawTexture3D
  64802. * @param data defines the data of the texture
  64803. * @param width defines the width of the texture
  64804. * @param height defines the height of the texture
  64805. * @param depth defines the depth of the texture
  64806. * @param format defines the texture format to use
  64807. * @param scene defines the hosting scene
  64808. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64809. * @param invertY defines if texture must be stored with Y axis inverted
  64810. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64811. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64812. */
  64813. function RawTexture3D(data, width, height, depth,
  64814. /** Gets or sets the texture format to use */
  64815. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64816. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64817. if (invertY === void 0) { invertY = false; }
  64818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64819. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64820. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64821. _this.format = format;
  64822. _this._engine = scene.getEngine();
  64823. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64824. _this.is3D = true;
  64825. return _this;
  64826. }
  64827. /**
  64828. * Update the texture with new data
  64829. * @param data defines the data to store in the texture
  64830. */
  64831. RawTexture3D.prototype.update = function (data) {
  64832. if (!this._texture) {
  64833. return;
  64834. }
  64835. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64836. };
  64837. return RawTexture3D;
  64838. }(BABYLON.Texture));
  64839. BABYLON.RawTexture3D = RawTexture3D;
  64840. })(BABYLON || (BABYLON = {}));
  64841. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64842. var BABYLON;
  64843. (function (BABYLON) {
  64844. /**
  64845. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64846. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64847. */
  64848. var PostProcessManager = /** @class */ (function () {
  64849. /**
  64850. * Creates a new instance PostProcess
  64851. * @param scene The scene that the post process is associated with.
  64852. */
  64853. function PostProcessManager(scene) {
  64854. this._vertexBuffers = {};
  64855. this._scene = scene;
  64856. }
  64857. PostProcessManager.prototype._prepareBuffers = function () {
  64858. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64859. return;
  64860. }
  64861. // VBO
  64862. var vertices = [];
  64863. vertices.push(1, 1);
  64864. vertices.push(-1, 1);
  64865. vertices.push(-1, -1);
  64866. vertices.push(1, -1);
  64867. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64868. this._buildIndexBuffer();
  64869. };
  64870. PostProcessManager.prototype._buildIndexBuffer = function () {
  64871. // Indices
  64872. var indices = [];
  64873. indices.push(0);
  64874. indices.push(1);
  64875. indices.push(2);
  64876. indices.push(0);
  64877. indices.push(2);
  64878. indices.push(3);
  64879. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64880. };
  64881. /**
  64882. * Rebuilds the vertex buffers of the manager.
  64883. */
  64884. PostProcessManager.prototype._rebuild = function () {
  64885. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64886. if (!vb) {
  64887. return;
  64888. }
  64889. vb._rebuild();
  64890. this._buildIndexBuffer();
  64891. };
  64892. // Methods
  64893. /**
  64894. * Prepares a frame to be run through a post process.
  64895. * @param sourceTexture The input texture to the post procesess. (default: null)
  64896. * @param postProcesses An array of post processes to be run. (default: null)
  64897. * @returns True if the post processes were able to be run.
  64898. */
  64899. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64900. if (sourceTexture === void 0) { sourceTexture = null; }
  64901. if (postProcesses === void 0) { postProcesses = null; }
  64902. var camera = this._scene.activeCamera;
  64903. if (!camera) {
  64904. return false;
  64905. }
  64906. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64907. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64908. return false;
  64909. }
  64910. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64911. return true;
  64912. };
  64913. /**
  64914. * Manually render a set of post processes to a texture.
  64915. * @param postProcesses An array of post processes to be run.
  64916. * @param targetTexture The target texture to render to.
  64917. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64918. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64919. * @param lodLevel defines which lod of the texture to render to
  64920. */
  64921. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64922. if (targetTexture === void 0) { targetTexture = null; }
  64923. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64924. if (faceIndex === void 0) { faceIndex = 0; }
  64925. if (lodLevel === void 0) { lodLevel = 0; }
  64926. var engine = this._scene.getEngine();
  64927. for (var index = 0; index < postProcesses.length; index++) {
  64928. if (index < postProcesses.length - 1) {
  64929. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64930. }
  64931. else {
  64932. if (targetTexture) {
  64933. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64934. }
  64935. else {
  64936. engine.restoreDefaultFramebuffer();
  64937. }
  64938. }
  64939. var pp = postProcesses[index];
  64940. var effect = pp.apply();
  64941. if (effect) {
  64942. pp.onBeforeRenderObservable.notifyObservers(effect);
  64943. // VBOs
  64944. this._prepareBuffers();
  64945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64946. // Draw order
  64947. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64948. pp.onAfterRenderObservable.notifyObservers(effect);
  64949. }
  64950. }
  64951. // Restore depth buffer
  64952. engine.setDepthBuffer(true);
  64953. engine.setDepthWrite(true);
  64954. };
  64955. /**
  64956. * Finalize the result of the output of the postprocesses.
  64957. * @param doNotPresent If true the result will not be displayed to the screen.
  64958. * @param targetTexture The target texture to render to.
  64959. * @param faceIndex The index of the face to bind the target texture to.
  64960. * @param postProcesses The array of post processes to render.
  64961. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64962. */
  64963. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64964. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64965. var camera = this._scene.activeCamera;
  64966. if (!camera) {
  64967. return;
  64968. }
  64969. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64970. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64971. return;
  64972. }
  64973. var engine = this._scene.getEngine();
  64974. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64975. var pp = postProcesses[index];
  64976. if (index < len - 1) {
  64977. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64978. }
  64979. else {
  64980. if (targetTexture) {
  64981. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64982. pp._outputTexture = targetTexture;
  64983. }
  64984. else {
  64985. engine.restoreDefaultFramebuffer();
  64986. pp._outputTexture = null;
  64987. }
  64988. }
  64989. if (doNotPresent) {
  64990. break;
  64991. }
  64992. var effect = pp.apply();
  64993. if (effect) {
  64994. pp.onBeforeRenderObservable.notifyObservers(effect);
  64995. // VBOs
  64996. this._prepareBuffers();
  64997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64998. // Draw order
  64999. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65000. pp.onAfterRenderObservable.notifyObservers(effect);
  65001. }
  65002. }
  65003. // Restore states
  65004. engine.setDepthBuffer(true);
  65005. engine.setDepthWrite(true);
  65006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65007. };
  65008. /**
  65009. * Disposes of the post process manager.
  65010. */
  65011. PostProcessManager.prototype.dispose = function () {
  65012. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65013. if (buffer) {
  65014. buffer.dispose();
  65015. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65016. }
  65017. if (this._indexBuffer) {
  65018. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65019. this._indexBuffer = null;
  65020. }
  65021. };
  65022. return PostProcessManager;
  65023. }());
  65024. BABYLON.PostProcessManager = PostProcessManager;
  65025. })(BABYLON || (BABYLON = {}));
  65026. //# sourceMappingURL=babylon.postProcessManager.js.map
  65027. var BABYLON;
  65028. (function (BABYLON) {
  65029. /**
  65030. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65031. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65032. */
  65033. var PostProcess = /** @class */ (function () {
  65034. /**
  65035. * Creates a new instance PostProcess
  65036. * @param name The name of the PostProcess.
  65037. * @param fragmentUrl The url of the fragment shader to be used.
  65038. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65039. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65040. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65041. * @param camera The camera to apply the render pass to.
  65042. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65043. * @param engine The engine which the post process will be applied. (default: current engine)
  65044. * @param reusable If the post process can be reused on the same frame. (default: false)
  65045. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65046. * @param textureType Type of textures used when performing the post process. (default: 0)
  65047. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65048. * @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
  65049. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65050. */
  65051. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65053. if (defines === void 0) { defines = null; }
  65054. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65055. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65056. if (blockCompilation === void 0) { blockCompilation = false; }
  65057. this.name = name;
  65058. /**
  65059. * Width of the texture to apply the post process on
  65060. */
  65061. this.width = -1;
  65062. /**
  65063. * Height of the texture to apply the post process on
  65064. */
  65065. this.height = -1;
  65066. /**
  65067. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65068. */
  65069. this._outputTexture = null;
  65070. /**
  65071. * If the buffer needs to be cleared before applying the post process. (default: true)
  65072. * Should be set to false if shader will overwrite all previous pixels.
  65073. */
  65074. this.autoClear = true;
  65075. /**
  65076. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65077. */
  65078. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65079. /**
  65080. * Animations to be used for the post processing
  65081. */
  65082. this.animations = new Array();
  65083. /**
  65084. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65085. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65086. */
  65087. this.enablePixelPerfectMode = false;
  65088. /**
  65089. * Force the postprocess to be applied without taking in account viewport
  65090. */
  65091. this.forceFullscreenViewport = true;
  65092. /**
  65093. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65094. *
  65095. * | Value | Type | Description |
  65096. * | ----- | ----------------------------------- | ----------- |
  65097. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65098. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65099. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65100. *
  65101. */
  65102. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65103. /**
  65104. * Force textures to be a power of two (default: false)
  65105. */
  65106. this.alwaysForcePOT = false;
  65107. /**
  65108. * Number of sample textures (default: 1)
  65109. */
  65110. this.samples = 1;
  65111. /**
  65112. * Modify the scale of the post process to be the same as the viewport (default: false)
  65113. */
  65114. this.adaptScaleToCurrentViewport = false;
  65115. this._reusable = false;
  65116. /**
  65117. * Smart array of input and output textures for the post process.
  65118. */
  65119. this._textures = new BABYLON.SmartArray(2);
  65120. /**
  65121. * The index in _textures that corresponds to the output texture.
  65122. */
  65123. this._currentRenderTextureInd = 0;
  65124. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65125. this._texelSize = BABYLON.Vector2.Zero();
  65126. // Events
  65127. /**
  65128. * An event triggered when the postprocess is activated.
  65129. */
  65130. this.onActivateObservable = new BABYLON.Observable();
  65131. /**
  65132. * An event triggered when the postprocess changes its size.
  65133. */
  65134. this.onSizeChangedObservable = new BABYLON.Observable();
  65135. /**
  65136. * An event triggered when the postprocess applies its effect.
  65137. */
  65138. this.onApplyObservable = new BABYLON.Observable();
  65139. /**
  65140. * An event triggered before rendering the postprocess
  65141. */
  65142. this.onBeforeRenderObservable = new BABYLON.Observable();
  65143. /**
  65144. * An event triggered after rendering the postprocess
  65145. */
  65146. this.onAfterRenderObservable = new BABYLON.Observable();
  65147. if (camera != null) {
  65148. this._camera = camera;
  65149. this._scene = camera.getScene();
  65150. camera.attachPostProcess(this);
  65151. this._engine = this._scene.getEngine();
  65152. this._scene.postProcesses.push(this);
  65153. }
  65154. else if (engine) {
  65155. this._engine = engine;
  65156. this._engine.postProcesses.push(this);
  65157. }
  65158. this._options = options;
  65159. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65160. this._reusable = reusable || false;
  65161. this._textureType = textureType;
  65162. this._samplers = samplers || [];
  65163. this._samplers.push("textureSampler");
  65164. this._fragmentUrl = fragmentUrl;
  65165. this._vertexUrl = vertexUrl;
  65166. this._parameters = parameters || [];
  65167. this._parameters.push("scale");
  65168. this._indexParameters = indexParameters;
  65169. if (!blockCompilation) {
  65170. this.updateEffect(defines);
  65171. }
  65172. }
  65173. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65174. /**
  65175. * A function that is added to the onActivateObservable
  65176. */
  65177. set: function (callback) {
  65178. if (this._onActivateObserver) {
  65179. this.onActivateObservable.remove(this._onActivateObserver);
  65180. }
  65181. if (callback) {
  65182. this._onActivateObserver = this.onActivateObservable.add(callback);
  65183. }
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65189. /**
  65190. * A function that is added to the onSizeChangedObservable
  65191. */
  65192. set: function (callback) {
  65193. if (this._onSizeChangedObserver) {
  65194. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65195. }
  65196. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65197. },
  65198. enumerable: true,
  65199. configurable: true
  65200. });
  65201. Object.defineProperty(PostProcess.prototype, "onApply", {
  65202. /**
  65203. * A function that is added to the onApplyObservable
  65204. */
  65205. set: function (callback) {
  65206. if (this._onApplyObserver) {
  65207. this.onApplyObservable.remove(this._onApplyObserver);
  65208. }
  65209. this._onApplyObserver = this.onApplyObservable.add(callback);
  65210. },
  65211. enumerable: true,
  65212. configurable: true
  65213. });
  65214. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65215. /**
  65216. * A function that is added to the onBeforeRenderObservable
  65217. */
  65218. set: function (callback) {
  65219. if (this._onBeforeRenderObserver) {
  65220. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65221. }
  65222. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65223. },
  65224. enumerable: true,
  65225. configurable: true
  65226. });
  65227. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65228. /**
  65229. * A function that is added to the onAfterRenderObservable
  65230. */
  65231. set: function (callback) {
  65232. if (this._onAfterRenderObserver) {
  65233. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65234. }
  65235. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65236. },
  65237. enumerable: true,
  65238. configurable: true
  65239. });
  65240. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65241. /**
  65242. * 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
  65243. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65244. */
  65245. get: function () {
  65246. return this._textures.data[this._currentRenderTextureInd];
  65247. },
  65248. set: function (value) {
  65249. this._forcedOutputTexture = value;
  65250. },
  65251. enumerable: true,
  65252. configurable: true
  65253. });
  65254. /**
  65255. * Gets the camera which post process is applied to.
  65256. * @returns The camera the post process is applied to.
  65257. */
  65258. PostProcess.prototype.getCamera = function () {
  65259. return this._camera;
  65260. };
  65261. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65262. /**
  65263. * Gets the texel size of the postprocess.
  65264. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65265. */
  65266. get: function () {
  65267. if (this._shareOutputWithPostProcess) {
  65268. return this._shareOutputWithPostProcess.texelSize;
  65269. }
  65270. if (this._forcedOutputTexture) {
  65271. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65272. }
  65273. return this._texelSize;
  65274. },
  65275. enumerable: true,
  65276. configurable: true
  65277. });
  65278. /**
  65279. * Gets the engine which this post process belongs to.
  65280. * @returns The engine the post process was enabled with.
  65281. */
  65282. PostProcess.prototype.getEngine = function () {
  65283. return this._engine;
  65284. };
  65285. /**
  65286. * The effect that is created when initializing the post process.
  65287. * @returns The created effect corrisponding the the postprocess.
  65288. */
  65289. PostProcess.prototype.getEffect = function () {
  65290. return this._effect;
  65291. };
  65292. /**
  65293. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65294. * @param postProcess The post process to share the output with.
  65295. * @returns This post process.
  65296. */
  65297. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65298. this._disposeTextures();
  65299. this._shareOutputWithPostProcess = postProcess;
  65300. return this;
  65301. };
  65302. /**
  65303. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65304. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65305. */
  65306. PostProcess.prototype.useOwnOutput = function () {
  65307. if (this._textures.length == 0) {
  65308. this._textures = new BABYLON.SmartArray(2);
  65309. }
  65310. this._shareOutputWithPostProcess = null;
  65311. };
  65312. /**
  65313. * Updates the effect with the current post process compile time values and recompiles the shader.
  65314. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65315. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65316. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65317. * @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
  65318. * @param onCompiled Called when the shader has been compiled.
  65319. * @param onError Called if there is an error when compiling a shader.
  65320. */
  65321. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65322. if (defines === void 0) { defines = null; }
  65323. if (uniforms === void 0) { uniforms = null; }
  65324. if (samplers === void 0) { samplers = null; }
  65325. 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);
  65326. };
  65327. /**
  65328. * The post process is reusable if it can be used multiple times within one frame.
  65329. * @returns If the post process is reusable
  65330. */
  65331. PostProcess.prototype.isReusable = function () {
  65332. return this._reusable;
  65333. };
  65334. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65335. PostProcess.prototype.markTextureDirty = function () {
  65336. this.width = -1;
  65337. };
  65338. /**
  65339. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65340. * 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.
  65341. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65342. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65343. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65344. * @returns The target texture that was bound to be written to.
  65345. */
  65346. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65347. var _this = this;
  65348. if (sourceTexture === void 0) { sourceTexture = null; }
  65349. camera = camera || this._camera;
  65350. var scene = camera.getScene();
  65351. var engine = scene.getEngine();
  65352. var maxSize = engine.getCaps().maxTextureSize;
  65353. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65354. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65355. // 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
  65356. var webVRCamera = camera.parent;
  65357. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65358. requiredWidth /= 2;
  65359. }
  65360. var desiredWidth = (this._options.width || requiredWidth);
  65361. var desiredHeight = this._options.height || requiredHeight;
  65362. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65363. if (this.adaptScaleToCurrentViewport) {
  65364. var currentViewport = engine.currentViewport;
  65365. if (currentViewport) {
  65366. desiredWidth *= currentViewport.width;
  65367. desiredHeight *= currentViewport.height;
  65368. }
  65369. }
  65370. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65371. if (!this._options.width) {
  65372. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65373. }
  65374. if (!this._options.height) {
  65375. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65376. }
  65377. }
  65378. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65379. if (this._textures.length > 0) {
  65380. for (var i = 0; i < this._textures.length; i++) {
  65381. this._engine._releaseTexture(this._textures.data[i]);
  65382. }
  65383. this._textures.reset();
  65384. }
  65385. this.width = desiredWidth;
  65386. this.height = desiredHeight;
  65387. var textureSize = { width: this.width, height: this.height };
  65388. var textureOptions = {
  65389. generateMipMaps: false,
  65390. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65391. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65392. samplingMode: this.renderTargetSamplingMode,
  65393. type: this._textureType
  65394. };
  65395. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65396. if (this._reusable) {
  65397. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65398. }
  65399. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65400. this.onSizeChangedObservable.notifyObservers(this);
  65401. }
  65402. this._textures.forEach(function (texture) {
  65403. if (texture.samples !== _this.samples) {
  65404. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65405. }
  65406. });
  65407. }
  65408. var target;
  65409. if (this._shareOutputWithPostProcess) {
  65410. target = this._shareOutputWithPostProcess.inputTexture;
  65411. }
  65412. else if (this._forcedOutputTexture) {
  65413. target = this._forcedOutputTexture;
  65414. this.width = this._forcedOutputTexture.width;
  65415. this.height = this._forcedOutputTexture.height;
  65416. }
  65417. else {
  65418. target = this.inputTexture;
  65419. }
  65420. // Bind the input of this post process to be used as the output of the previous post process.
  65421. if (this.enablePixelPerfectMode) {
  65422. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65423. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65424. }
  65425. else {
  65426. this._scaleRatio.copyFromFloats(1, 1);
  65427. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65428. }
  65429. this.onActivateObservable.notifyObservers(camera);
  65430. // Clear
  65431. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65432. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65433. }
  65434. if (this._reusable) {
  65435. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65436. }
  65437. return target;
  65438. };
  65439. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65440. /**
  65441. * If the post process is supported.
  65442. */
  65443. get: function () {
  65444. return this._effect.isSupported;
  65445. },
  65446. enumerable: true,
  65447. configurable: true
  65448. });
  65449. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65450. /**
  65451. * The aspect ratio of the output texture.
  65452. */
  65453. get: function () {
  65454. if (this._shareOutputWithPostProcess) {
  65455. return this._shareOutputWithPostProcess.aspectRatio;
  65456. }
  65457. if (this._forcedOutputTexture) {
  65458. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65459. }
  65460. return this.width / this.height;
  65461. },
  65462. enumerable: true,
  65463. configurable: true
  65464. });
  65465. /**
  65466. * Get a value indicating if the post-process is ready to be used
  65467. * @returns true if the post-process is ready (shader is compiled)
  65468. */
  65469. PostProcess.prototype.isReady = function () {
  65470. return this._effect && this._effect.isReady();
  65471. };
  65472. /**
  65473. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65474. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65475. */
  65476. PostProcess.prototype.apply = function () {
  65477. // Check
  65478. if (!this._effect || !this._effect.isReady())
  65479. return null;
  65480. // States
  65481. this._engine.enableEffect(this._effect);
  65482. this._engine.setState(false);
  65483. this._engine.setDepthBuffer(false);
  65484. this._engine.setDepthWrite(false);
  65485. // Alpha
  65486. this._engine.setAlphaMode(this.alphaMode);
  65487. if (this.alphaConstants) {
  65488. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65489. }
  65490. // Bind the output texture of the preivous post process as the input to this post process.
  65491. var source;
  65492. if (this._shareOutputWithPostProcess) {
  65493. source = this._shareOutputWithPostProcess.inputTexture;
  65494. }
  65495. else if (this._forcedOutputTexture) {
  65496. source = this._forcedOutputTexture;
  65497. }
  65498. else {
  65499. source = this.inputTexture;
  65500. }
  65501. this._effect._bindTexture("textureSampler", source);
  65502. // Parameters
  65503. this._effect.setVector2("scale", this._scaleRatio);
  65504. this.onApplyObservable.notifyObservers(this._effect);
  65505. return this._effect;
  65506. };
  65507. PostProcess.prototype._disposeTextures = function () {
  65508. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65509. return;
  65510. }
  65511. if (this._textures.length > 0) {
  65512. for (var i = 0; i < this._textures.length; i++) {
  65513. this._engine._releaseTexture(this._textures.data[i]);
  65514. }
  65515. }
  65516. this._textures.dispose();
  65517. };
  65518. /**
  65519. * Disposes the post process.
  65520. * @param camera The camera to dispose the post process on.
  65521. */
  65522. PostProcess.prototype.dispose = function (camera) {
  65523. camera = camera || this._camera;
  65524. this._disposeTextures();
  65525. if (this._scene) {
  65526. var index_1 = this._scene.postProcesses.indexOf(this);
  65527. if (index_1 !== -1) {
  65528. this._scene.postProcesses.splice(index_1, 1);
  65529. }
  65530. }
  65531. else {
  65532. var index_2 = this._engine.postProcesses.indexOf(this);
  65533. if (index_2 !== -1) {
  65534. this._engine.postProcesses.splice(index_2, 1);
  65535. }
  65536. }
  65537. if (!camera) {
  65538. return;
  65539. }
  65540. camera.detachPostProcess(this);
  65541. var index = camera._postProcesses.indexOf(this);
  65542. if (index === 0 && camera._postProcesses.length > 0) {
  65543. var firstPostProcess = this._camera._getFirstPostProcess();
  65544. if (firstPostProcess) {
  65545. firstPostProcess.markTextureDirty();
  65546. }
  65547. }
  65548. this.onActivateObservable.clear();
  65549. this.onAfterRenderObservable.clear();
  65550. this.onApplyObservable.clear();
  65551. this.onBeforeRenderObservable.clear();
  65552. this.onSizeChangedObservable.clear();
  65553. };
  65554. return PostProcess;
  65555. }());
  65556. BABYLON.PostProcess = PostProcess;
  65557. })(BABYLON || (BABYLON = {}));
  65558. //# sourceMappingURL=babylon.postProcess.js.map
  65559. var BABYLON;
  65560. (function (BABYLON) {
  65561. var PassPostProcess = /** @class */ (function (_super) {
  65562. __extends(PassPostProcess, _super);
  65563. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65564. if (camera === void 0) { camera = null; }
  65565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65566. if (blockCompilation === void 0) { blockCompilation = false; }
  65567. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65568. }
  65569. return PassPostProcess;
  65570. }(BABYLON.PostProcess));
  65571. BABYLON.PassPostProcess = PassPostProcess;
  65572. })(BABYLON || (BABYLON = {}));
  65573. //# sourceMappingURL=babylon.passPostProcess.js.map
  65574. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65575. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65576. s = arguments[i];
  65577. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65578. t[p] = s[p];
  65579. }
  65580. return t;
  65581. };
  65582. var BABYLON;
  65583. (function (BABYLON) {
  65584. /**
  65585. * Default implementation IShadowGenerator.
  65586. * This is the main object responsible of generating shadows in the framework.
  65587. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65588. */
  65589. var ShadowGenerator = /** @class */ (function () {
  65590. /**
  65591. * Creates a ShadowGenerator object.
  65592. * A ShadowGenerator is the required tool to use the shadows.
  65593. * Each light casting shadows needs to use its own ShadowGenerator.
  65594. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65595. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65596. * @param light The light object generating the shadows.
  65597. * @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.
  65598. */
  65599. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65600. this._bias = 0.00005;
  65601. this._normalBias = 0;
  65602. this._blurBoxOffset = 1;
  65603. this._blurScale = 2;
  65604. this._blurKernel = 1;
  65605. this._useKernelBlur = false;
  65606. this._filter = ShadowGenerator.FILTER_NONE;
  65607. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65608. this._contactHardeningLightSizeUVRatio = 0.1;
  65609. this._darkness = 0;
  65610. this._transparencyShadow = false;
  65611. /**
  65612. * Controls the extent to which the shadows fade out at the edge of the frustum
  65613. * Used only by directionals and spots
  65614. */
  65615. this.frustumEdgeFalloff = 0;
  65616. /**
  65617. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65618. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65619. * It might on the other hand introduce peter panning.
  65620. */
  65621. this.forceBackFacesOnly = false;
  65622. this._lightDirection = BABYLON.Vector3.Zero();
  65623. this._viewMatrix = BABYLON.Matrix.Zero();
  65624. this._projectionMatrix = BABYLON.Matrix.Zero();
  65625. this._transformMatrix = BABYLON.Matrix.Zero();
  65626. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65627. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65628. this._currentFaceIndex = 0;
  65629. this._currentFaceIndexCache = 0;
  65630. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65631. this._mapSize = mapSize;
  65632. this._light = light;
  65633. this._scene = light.getScene();
  65634. light._shadowGenerator = this;
  65635. // Texture type fallback from float to int if not supported.
  65636. var caps = this._scene.getEngine().getCaps();
  65637. if (!useFullFloatFirst) {
  65638. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65639. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65640. }
  65641. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65642. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65643. }
  65644. else {
  65645. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65646. }
  65647. }
  65648. else {
  65649. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65650. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65651. }
  65652. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65653. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65654. }
  65655. else {
  65656. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65657. }
  65658. }
  65659. this._initializeGenerator();
  65660. this._applyFilterValues();
  65661. }
  65662. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65663. /**
  65664. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65665. */
  65666. get: function () {
  65667. return this._bias;
  65668. },
  65669. /**
  65670. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65671. */
  65672. set: function (bias) {
  65673. this._bias = bias;
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65679. /**
  65680. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65681. */
  65682. get: function () {
  65683. return this._normalBias;
  65684. },
  65685. /**
  65686. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65687. */
  65688. set: function (normalBias) {
  65689. this._normalBias = normalBias;
  65690. },
  65691. enumerable: true,
  65692. configurable: true
  65693. });
  65694. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65695. /**
  65696. * Gets the blur box offset: offset applied during the blur pass.
  65697. * Only usefull if useKernelBlur = false
  65698. */
  65699. get: function () {
  65700. return this._blurBoxOffset;
  65701. },
  65702. /**
  65703. * Sets the blur box offset: offset applied during the blur pass.
  65704. * Only usefull if useKernelBlur = false
  65705. */
  65706. set: function (value) {
  65707. if (this._blurBoxOffset === value) {
  65708. return;
  65709. }
  65710. this._blurBoxOffset = value;
  65711. this._disposeBlurPostProcesses();
  65712. },
  65713. enumerable: true,
  65714. configurable: true
  65715. });
  65716. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65717. /**
  65718. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65719. * 2 means half of the size.
  65720. */
  65721. get: function () {
  65722. return this._blurScale;
  65723. },
  65724. /**
  65725. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65726. * 2 means half of the size.
  65727. */
  65728. set: function (value) {
  65729. if (this._blurScale === value) {
  65730. return;
  65731. }
  65732. this._blurScale = value;
  65733. this._disposeBlurPostProcesses();
  65734. },
  65735. enumerable: true,
  65736. configurable: true
  65737. });
  65738. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65739. /**
  65740. * Gets the blur kernel: kernel size of the blur pass.
  65741. * Only usefull if useKernelBlur = true
  65742. */
  65743. get: function () {
  65744. return this._blurKernel;
  65745. },
  65746. /**
  65747. * Sets the blur kernel: kernel size of the blur pass.
  65748. * Only usefull if useKernelBlur = true
  65749. */
  65750. set: function (value) {
  65751. if (this._blurKernel === value) {
  65752. return;
  65753. }
  65754. this._blurKernel = value;
  65755. this._disposeBlurPostProcesses();
  65756. },
  65757. enumerable: true,
  65758. configurable: true
  65759. });
  65760. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65761. /**
  65762. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65763. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65764. */
  65765. get: function () {
  65766. return this._useKernelBlur;
  65767. },
  65768. /**
  65769. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65770. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65771. */
  65772. set: function (value) {
  65773. if (this._useKernelBlur === value) {
  65774. return;
  65775. }
  65776. this._useKernelBlur = value;
  65777. this._disposeBlurPostProcesses();
  65778. },
  65779. enumerable: true,
  65780. configurable: true
  65781. });
  65782. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65783. /**
  65784. * Gets the depth scale used in ESM mode.
  65785. */
  65786. get: function () {
  65787. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65788. },
  65789. /**
  65790. * Sets the depth scale used in ESM mode.
  65791. * This can override the scale stored on the light.
  65792. */
  65793. set: function (value) {
  65794. this._depthScale = value;
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65800. /**
  65801. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65802. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65803. */
  65804. get: function () {
  65805. return this._filter;
  65806. },
  65807. /**
  65808. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65809. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65810. */
  65811. set: function (value) {
  65812. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65813. if (this._light.needCube()) {
  65814. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65815. this.useExponentialShadowMap = true;
  65816. return;
  65817. }
  65818. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65819. this.useCloseExponentialShadowMap = true;
  65820. return;
  65821. }
  65822. // PCF on cubemap would also be expensive
  65823. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65824. this.usePoissonSampling = true;
  65825. return;
  65826. }
  65827. }
  65828. // Weblg1 fallback for PCF.
  65829. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65830. if (this._scene.getEngine().webGLVersion === 1) {
  65831. this.usePoissonSampling = true;
  65832. return;
  65833. }
  65834. }
  65835. if (this._filter === value) {
  65836. return;
  65837. }
  65838. this._filter = value;
  65839. this._disposeBlurPostProcesses();
  65840. this._applyFilterValues();
  65841. this._light._markMeshesAsLightDirty();
  65842. },
  65843. enumerable: true,
  65844. configurable: true
  65845. });
  65846. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65847. /**
  65848. * Gets if the current filter is set to Poisson Sampling.
  65849. */
  65850. get: function () {
  65851. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65852. },
  65853. /**
  65854. * Sets the current filter to Poisson Sampling.
  65855. */
  65856. set: function (value) {
  65857. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65858. return;
  65859. }
  65860. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65861. },
  65862. enumerable: true,
  65863. configurable: true
  65864. });
  65865. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65866. /**
  65867. * Gets if the current filter is set to VSM.
  65868. * DEPRECATED. Should use useExponentialShadowMap instead.
  65869. */
  65870. get: function () {
  65871. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65872. return this.useExponentialShadowMap;
  65873. },
  65874. /**
  65875. * Sets the current filter is to VSM.
  65876. * DEPRECATED. Should use useExponentialShadowMap instead.
  65877. */
  65878. set: function (value) {
  65879. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65880. this.useExponentialShadowMap = value;
  65881. },
  65882. enumerable: true,
  65883. configurable: true
  65884. });
  65885. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65886. /**
  65887. * Gets if the current filter is set to blurred VSM.
  65888. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65889. */
  65890. get: function () {
  65891. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65892. return this.useBlurExponentialShadowMap;
  65893. },
  65894. /**
  65895. * Sets the current filter is to blurred VSM.
  65896. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65897. */
  65898. set: function (value) {
  65899. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65900. this.useBlurExponentialShadowMap = value;
  65901. },
  65902. enumerable: true,
  65903. configurable: true
  65904. });
  65905. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65906. /**
  65907. * Gets if the current filter is set to ESM.
  65908. */
  65909. get: function () {
  65910. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65911. },
  65912. /**
  65913. * Sets the current filter is to ESM.
  65914. */
  65915. set: function (value) {
  65916. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65917. return;
  65918. }
  65919. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65925. /**
  65926. * Gets if the current filter is set to filtered ESM.
  65927. */
  65928. get: function () {
  65929. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65930. },
  65931. /**
  65932. * Gets if the current filter is set to filtered ESM.
  65933. */
  65934. set: function (value) {
  65935. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65936. return;
  65937. }
  65938. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65939. },
  65940. enumerable: true,
  65941. configurable: true
  65942. });
  65943. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65944. /**
  65945. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65946. * exponential to prevent steep falloff artifacts).
  65947. */
  65948. get: function () {
  65949. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65950. },
  65951. /**
  65952. * Sets the current filter to "close ESM" (using the inverse of the
  65953. * exponential to prevent steep falloff artifacts).
  65954. */
  65955. set: function (value) {
  65956. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65957. return;
  65958. }
  65959. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65960. },
  65961. enumerable: true,
  65962. configurable: true
  65963. });
  65964. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65965. /**
  65966. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65967. * exponential to prevent steep falloff artifacts).
  65968. */
  65969. get: function () {
  65970. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65971. },
  65972. /**
  65973. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65974. * exponential to prevent steep falloff artifacts).
  65975. */
  65976. set: function (value) {
  65977. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65978. return;
  65979. }
  65980. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65981. },
  65982. enumerable: true,
  65983. configurable: true
  65984. });
  65985. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65986. /**
  65987. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65988. */
  65989. get: function () {
  65990. return this.filter === ShadowGenerator.FILTER_PCF;
  65991. },
  65992. /**
  65993. * Sets the current filter to "PCF" (percentage closer filtering).
  65994. */
  65995. set: function (value) {
  65996. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65997. return;
  65998. }
  65999. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66000. },
  66001. enumerable: true,
  66002. configurable: true
  66003. });
  66004. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66005. /**
  66006. * Gets the PCF or PCSS Quality.
  66007. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66008. */
  66009. get: function () {
  66010. return this._filteringQuality;
  66011. },
  66012. /**
  66013. * Sets the PCF or PCSS Quality.
  66014. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66015. */
  66016. set: function (filteringQuality) {
  66017. this._filteringQuality = filteringQuality;
  66018. },
  66019. enumerable: true,
  66020. configurable: true
  66021. });
  66022. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66023. /**
  66024. * Gets if the current filter is set to "PCSS" (contact hardening).
  66025. */
  66026. get: function () {
  66027. return this.filter === ShadowGenerator.FILTER_PCSS;
  66028. },
  66029. /**
  66030. * Sets the current filter to "PCSS" (contact hardening).
  66031. */
  66032. set: function (value) {
  66033. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66034. return;
  66035. }
  66036. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66042. /**
  66043. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66044. * Using a ratio helps keeping shape stability independently of the map size.
  66045. *
  66046. * It does not account for the light projection as it was having too much
  66047. * instability during the light setup or during light position changes.
  66048. *
  66049. * Only valid if useContactHardeningShadow is true.
  66050. */
  66051. get: function () {
  66052. return this._contactHardeningLightSizeUVRatio;
  66053. },
  66054. /**
  66055. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66056. * Using a ratio helps keeping shape stability independently of the map size.
  66057. *
  66058. * It does not account for the light projection as it was having too much
  66059. * instability during the light setup or during light position changes.
  66060. *
  66061. * Only valid if useContactHardeningShadow is true.
  66062. */
  66063. set: function (contactHardeningLightSizeUVRatio) {
  66064. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66065. },
  66066. enumerable: true,
  66067. configurable: true
  66068. });
  66069. /**
  66070. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66071. * 0 means strongest and 1 would means no shadow.
  66072. * @returns the darkness.
  66073. */
  66074. ShadowGenerator.prototype.getDarkness = function () {
  66075. return this._darkness;
  66076. };
  66077. /**
  66078. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66079. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66080. * @returns the shadow generator allowing fluent coding.
  66081. */
  66082. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66083. if (darkness >= 1.0)
  66084. this._darkness = 1.0;
  66085. else if (darkness <= 0.0)
  66086. this._darkness = 0.0;
  66087. else
  66088. this._darkness = darkness;
  66089. return this;
  66090. };
  66091. /**
  66092. * Sets the ability to have transparent shadow (boolean).
  66093. * @param transparent True if transparent else False
  66094. * @returns the shadow generator allowing fluent coding
  66095. */
  66096. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66097. this._transparencyShadow = transparent;
  66098. return this;
  66099. };
  66100. /**
  66101. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66102. * @returns The render target texture if present otherwise, null
  66103. */
  66104. ShadowGenerator.prototype.getShadowMap = function () {
  66105. return this._shadowMap;
  66106. };
  66107. /**
  66108. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66109. * @returns The render target texture if the shadow map is present otherwise, null
  66110. */
  66111. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66112. if (this._shadowMap2) {
  66113. return this._shadowMap2;
  66114. }
  66115. return this._shadowMap;
  66116. };
  66117. /**
  66118. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66119. * @param mesh Mesh to add
  66120. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66121. * @returns the Shadow Generator itself
  66122. */
  66123. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66124. if (includeDescendants === void 0) { includeDescendants = true; }
  66125. if (!this._shadowMap) {
  66126. return this;
  66127. }
  66128. if (!this._shadowMap.renderList) {
  66129. this._shadowMap.renderList = [];
  66130. }
  66131. this._shadowMap.renderList.push(mesh);
  66132. if (includeDescendants) {
  66133. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66134. }
  66135. return this;
  66136. var _a;
  66137. };
  66138. /**
  66139. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66140. * @param mesh Mesh to remove
  66141. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66142. * @returns the Shadow Generator itself
  66143. */
  66144. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66145. if (includeDescendants === void 0) { includeDescendants = true; }
  66146. if (!this._shadowMap || !this._shadowMap.renderList) {
  66147. return this;
  66148. }
  66149. var index = this._shadowMap.renderList.indexOf(mesh);
  66150. if (index !== -1) {
  66151. this._shadowMap.renderList.splice(index, 1);
  66152. }
  66153. if (includeDescendants) {
  66154. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66155. var child = _a[_i];
  66156. this.removeShadowCaster(child);
  66157. }
  66158. }
  66159. return this;
  66160. };
  66161. /**
  66162. * Returns the associated light object.
  66163. * @returns the light generating the shadow
  66164. */
  66165. ShadowGenerator.prototype.getLight = function () {
  66166. return this._light;
  66167. };
  66168. ShadowGenerator.prototype._initializeGenerator = function () {
  66169. this._light._markMeshesAsLightDirty();
  66170. this._initializeShadowMap();
  66171. };
  66172. ShadowGenerator.prototype._initializeShadowMap = function () {
  66173. var _this = this;
  66174. // Render target
  66175. var engine = this._scene.getEngine();
  66176. if (engine.webGLVersion > 1) {
  66177. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66178. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66179. }
  66180. else {
  66181. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66182. }
  66183. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66184. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66185. this._shadowMap.anisotropicFilteringLevel = 1;
  66186. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66187. this._shadowMap.renderParticles = false;
  66188. this._shadowMap.ignoreCameraViewport = true;
  66189. // Record Face Index before render.
  66190. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66191. _this._currentFaceIndex = faceIndex;
  66192. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66193. engine.setColorWrite(false);
  66194. }
  66195. });
  66196. // Custom render function.
  66197. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66198. // Blur if required afer render.
  66199. this._shadowMap.onAfterUnbindObservable.add(function () {
  66200. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66201. engine.setColorWrite(true);
  66202. }
  66203. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66204. return;
  66205. }
  66206. var shadowMap = _this.getShadowMapForRendering();
  66207. if (shadowMap) {
  66208. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66209. }
  66210. });
  66211. // Clear according to the chosen filter.
  66212. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66213. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66214. this._shadowMap.onClearObservable.add(function (engine) {
  66215. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66216. engine.clear(clearOne, false, true, false);
  66217. }
  66218. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66219. engine.clear(clearZero, true, true, false);
  66220. }
  66221. else {
  66222. engine.clear(clearOne, true, true, false);
  66223. }
  66224. });
  66225. };
  66226. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66227. var _this = this;
  66228. var engine = this._scene.getEngine();
  66229. var targetSize = this._mapSize / this.blurScale;
  66230. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66231. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66232. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66233. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66234. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66235. }
  66236. if (this.useKernelBlur) {
  66237. 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);
  66238. this._kernelBlurXPostprocess.width = targetSize;
  66239. this._kernelBlurXPostprocess.height = targetSize;
  66240. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66241. effect.setTexture("textureSampler", _this._shadowMap);
  66242. });
  66243. 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);
  66244. this._kernelBlurXPostprocess.autoClear = false;
  66245. this._kernelBlurYPostprocess.autoClear = false;
  66246. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66247. this._kernelBlurXPostprocess.packedFloat = true;
  66248. this._kernelBlurYPostprocess.packedFloat = true;
  66249. }
  66250. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66251. }
  66252. else {
  66253. 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);
  66254. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66255. effect.setFloat2("screenSize", targetSize, targetSize);
  66256. effect.setTexture("textureSampler", _this._shadowMap);
  66257. });
  66258. this._boxBlurPostprocess.autoClear = false;
  66259. this._blurPostProcesses = [this._boxBlurPostprocess];
  66260. }
  66261. };
  66262. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66263. var index;
  66264. var engine = this._scene.getEngine();
  66265. if (depthOnlySubMeshes.length) {
  66266. engine.setColorWrite(false);
  66267. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66268. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66269. }
  66270. engine.setColorWrite(true);
  66271. }
  66272. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66273. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66274. }
  66275. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66276. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66277. }
  66278. if (this._transparencyShadow) {
  66279. for (index = 0; index < transparentSubMeshes.length; index++) {
  66280. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66281. }
  66282. }
  66283. };
  66284. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66285. var _this = this;
  66286. var mesh = subMesh.getRenderingMesh();
  66287. var scene = this._scene;
  66288. var engine = scene.getEngine();
  66289. var material = subMesh.getMaterial();
  66290. if (!material) {
  66291. return;
  66292. }
  66293. // Culling
  66294. engine.setState(material.backFaceCulling);
  66295. // Managing instances
  66296. var batch = mesh._getInstancesRenderList(subMesh._id);
  66297. if (batch.mustReturn) {
  66298. return;
  66299. }
  66300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66301. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66302. engine.enableEffect(this._effect);
  66303. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66304. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66305. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66306. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66307. this._effect.setVector3("lightData", this._cachedDirection);
  66308. }
  66309. else {
  66310. this._effect.setVector3("lightData", this._cachedPosition);
  66311. }
  66312. if (scene.activeCamera) {
  66313. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66314. }
  66315. // Alpha test
  66316. if (material && material.needAlphaTesting()) {
  66317. var alphaTexture = material.getAlphaTestTexture();
  66318. if (alphaTexture) {
  66319. this._effect.setTexture("diffuseSampler", alphaTexture);
  66320. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66321. }
  66322. }
  66323. // Bones
  66324. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66325. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66326. }
  66327. // Morph targets
  66328. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66329. if (this.forceBackFacesOnly) {
  66330. engine.setState(true, 0, false, true);
  66331. }
  66332. // Draw
  66333. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66334. if (this.forceBackFacesOnly) {
  66335. engine.setState(true, 0, false, false);
  66336. }
  66337. }
  66338. else {
  66339. // Need to reset refresh rate of the shadowMap
  66340. if (this._shadowMap) {
  66341. this._shadowMap.resetRefreshCounter();
  66342. }
  66343. }
  66344. };
  66345. ShadowGenerator.prototype._applyFilterValues = function () {
  66346. if (!this._shadowMap) {
  66347. return;
  66348. }
  66349. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66350. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66351. }
  66352. else {
  66353. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66354. }
  66355. };
  66356. /**
  66357. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66358. * @param onCompiled Callback triggered at the and of the effects compilation
  66359. * @param options Sets of optional options forcing the compilation with different modes
  66360. */
  66361. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66362. var _this = this;
  66363. var localOptions = __assign({ useInstances: false }, options);
  66364. var shadowMap = this.getShadowMap();
  66365. if (!shadowMap) {
  66366. if (onCompiled) {
  66367. onCompiled(this);
  66368. }
  66369. return;
  66370. }
  66371. var renderList = shadowMap.renderList;
  66372. if (!renderList) {
  66373. if (onCompiled) {
  66374. onCompiled(this);
  66375. }
  66376. return;
  66377. }
  66378. var subMeshes = new Array();
  66379. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66380. var mesh = renderList_1[_i];
  66381. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66382. }
  66383. if (subMeshes.length === 0) {
  66384. if (onCompiled) {
  66385. onCompiled(this);
  66386. }
  66387. return;
  66388. }
  66389. var currentIndex = 0;
  66390. var checkReady = function () {
  66391. if (!_this._scene || !_this._scene.getEngine()) {
  66392. return;
  66393. }
  66394. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66395. currentIndex++;
  66396. if (currentIndex >= subMeshes.length) {
  66397. if (onCompiled) {
  66398. onCompiled(_this);
  66399. }
  66400. return;
  66401. }
  66402. }
  66403. setTimeout(checkReady, 16);
  66404. };
  66405. checkReady();
  66406. };
  66407. /**
  66408. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66409. * @param options Sets of optional options forcing the compilation with different modes
  66410. * @returns A promise that resolves when the compilation completes
  66411. */
  66412. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66413. var _this = this;
  66414. return new Promise(function (resolve) {
  66415. _this.forceCompilation(function () {
  66416. resolve();
  66417. }, options);
  66418. });
  66419. };
  66420. /**
  66421. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66422. * @param subMesh The submesh we want to render in the shadow map
  66423. * @param useInstances Defines wether will draw in the map using instances
  66424. * @returns true if ready otherwise, false
  66425. */
  66426. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66427. var defines = [];
  66428. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66429. defines.push("#define FLOAT");
  66430. }
  66431. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66432. defines.push("#define ESM");
  66433. }
  66434. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66435. defines.push("#define DEPTHTEXTURE");
  66436. }
  66437. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66438. var mesh = subMesh.getMesh();
  66439. var material = subMesh.getMaterial();
  66440. // Normal bias.
  66441. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66442. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66443. defines.push("#define NORMAL");
  66444. if (mesh.nonUniformScaling) {
  66445. defines.push("#define NONUNIFORMSCALING");
  66446. }
  66447. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66448. defines.push("#define DIRECTIONINLIGHTDATA");
  66449. }
  66450. }
  66451. // Alpha test
  66452. if (material && material.needAlphaTesting()) {
  66453. var alphaTexture = material.getAlphaTestTexture();
  66454. if (alphaTexture) {
  66455. defines.push("#define ALPHATEST");
  66456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66457. attribs.push(BABYLON.VertexBuffer.UVKind);
  66458. defines.push("#define UV1");
  66459. }
  66460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66461. if (alphaTexture.coordinatesIndex === 1) {
  66462. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66463. defines.push("#define UV2");
  66464. }
  66465. }
  66466. }
  66467. }
  66468. // Bones
  66469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66472. if (mesh.numBoneInfluencers > 4) {
  66473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66475. }
  66476. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66477. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66478. }
  66479. else {
  66480. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66481. }
  66482. // Morph targets
  66483. var manager = mesh.morphTargetManager;
  66484. var morphInfluencers = 0;
  66485. if (manager) {
  66486. if (manager.numInfluencers > 0) {
  66487. defines.push("#define MORPHTARGETS");
  66488. morphInfluencers = manager.numInfluencers;
  66489. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66490. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66491. }
  66492. }
  66493. // Instances
  66494. if (useInstances) {
  66495. defines.push("#define INSTANCES");
  66496. attribs.push("world0");
  66497. attribs.push("world1");
  66498. attribs.push("world2");
  66499. attribs.push("world3");
  66500. }
  66501. // Get correct effect
  66502. var join = defines.join("\n");
  66503. if (this._cachedDefines !== join) {
  66504. this._cachedDefines = join;
  66505. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66506. }
  66507. if (!this._effect.isReady()) {
  66508. return false;
  66509. }
  66510. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66511. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66512. this._initializeBlurRTTAndPostProcesses();
  66513. }
  66514. }
  66515. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66516. return false;
  66517. }
  66518. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66519. return false;
  66520. }
  66521. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66522. return false;
  66523. }
  66524. return true;
  66525. };
  66526. /**
  66527. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66528. * @param defines Defines of the material we want to update
  66529. * @param lightIndex Index of the light in the enabled light list of the material
  66530. */
  66531. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66532. var scene = this._scene;
  66533. var light = this._light;
  66534. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66535. return;
  66536. }
  66537. defines["SHADOW" + lightIndex] = true;
  66538. if (this.useContactHardeningShadow) {
  66539. defines["SHADOWPCSS" + lightIndex] = true;
  66540. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66541. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66542. }
  66543. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66544. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66545. }
  66546. // else default to high.
  66547. }
  66548. if (this.usePercentageCloserFiltering) {
  66549. defines["SHADOWPCF" + lightIndex] = true;
  66550. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66551. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66552. }
  66553. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66554. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66555. }
  66556. // else default to high.
  66557. }
  66558. else if (this.usePoissonSampling) {
  66559. defines["SHADOWPOISSON" + lightIndex] = true;
  66560. }
  66561. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66562. defines["SHADOWESM" + lightIndex] = true;
  66563. }
  66564. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66565. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66566. }
  66567. if (light.needCube()) {
  66568. defines["SHADOWCUBE" + lightIndex] = true;
  66569. }
  66570. };
  66571. /**
  66572. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66573. * defined in the generator but impacting the effect).
  66574. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66575. * @param effect The effect we are binfing the information for
  66576. */
  66577. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66578. var light = this._light;
  66579. var scene = this._scene;
  66580. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66581. return;
  66582. }
  66583. var camera = scene.activeCamera;
  66584. if (!camera) {
  66585. return;
  66586. }
  66587. var shadowMap = this.getShadowMap();
  66588. if (!shadowMap) {
  66589. return;
  66590. }
  66591. if (!light.needCube()) {
  66592. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66593. }
  66594. // Only PCF uses depth stencil texture.
  66595. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66596. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66597. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66598. }
  66599. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66600. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66601. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66602. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66603. }
  66604. else {
  66605. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66606. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66607. }
  66608. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66609. };
  66610. /**
  66611. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66612. * (eq to shadow prjection matrix * light transform matrix)
  66613. * @returns The transform matrix used to create the shadow map
  66614. */
  66615. ShadowGenerator.prototype.getTransformMatrix = function () {
  66616. var scene = this._scene;
  66617. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66618. return this._transformMatrix;
  66619. }
  66620. this._currentRenderID = scene.getRenderId();
  66621. this._currentFaceIndexCache = this._currentFaceIndex;
  66622. var lightPosition = this._light.position;
  66623. if (this._light.computeTransformedInformation()) {
  66624. lightPosition = this._light.transformedPosition;
  66625. }
  66626. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66627. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66628. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66629. }
  66630. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66631. this._cachedPosition.copyFrom(lightPosition);
  66632. this._cachedDirection.copyFrom(this._lightDirection);
  66633. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66634. var shadowMap = this.getShadowMap();
  66635. if (shadowMap) {
  66636. var renderList = shadowMap.renderList;
  66637. if (renderList) {
  66638. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66639. }
  66640. }
  66641. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66642. }
  66643. return this._transformMatrix;
  66644. };
  66645. /**
  66646. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66647. * Cube and 2D textures for instance.
  66648. */
  66649. ShadowGenerator.prototype.recreateShadowMap = function () {
  66650. var shadowMap = this._shadowMap;
  66651. if (!shadowMap) {
  66652. return;
  66653. }
  66654. // Track render list.
  66655. var renderList = shadowMap.renderList;
  66656. // Clean up existing data.
  66657. this._disposeRTTandPostProcesses();
  66658. // Reinitializes.
  66659. this._initializeGenerator();
  66660. // Reaffect the filter to ensure a correct fallback if necessary.
  66661. this.filter = this.filter;
  66662. // Reaffect the filter.
  66663. this._applyFilterValues();
  66664. // Reaffect Render List.
  66665. this._shadowMap.renderList = renderList;
  66666. };
  66667. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66668. if (this._shadowMap2) {
  66669. this._shadowMap2.dispose();
  66670. this._shadowMap2 = null;
  66671. }
  66672. if (this._boxBlurPostprocess) {
  66673. this._boxBlurPostprocess.dispose();
  66674. this._boxBlurPostprocess = null;
  66675. }
  66676. if (this._kernelBlurXPostprocess) {
  66677. this._kernelBlurXPostprocess.dispose();
  66678. this._kernelBlurXPostprocess = null;
  66679. }
  66680. if (this._kernelBlurYPostprocess) {
  66681. this._kernelBlurYPostprocess.dispose();
  66682. this._kernelBlurYPostprocess = null;
  66683. }
  66684. this._blurPostProcesses = [];
  66685. };
  66686. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66687. if (this._shadowMap) {
  66688. this._shadowMap.dispose();
  66689. this._shadowMap = null;
  66690. }
  66691. this._disposeBlurPostProcesses();
  66692. };
  66693. /**
  66694. * Disposes the ShadowGenerator.
  66695. * Returns nothing.
  66696. */
  66697. ShadowGenerator.prototype.dispose = function () {
  66698. this._disposeRTTandPostProcesses();
  66699. if (this._light) {
  66700. this._light._shadowGenerator = null;
  66701. this._light._markMeshesAsLightDirty();
  66702. }
  66703. };
  66704. /**
  66705. * Serializes the shadow generator setup to a json object.
  66706. * @returns The serialized JSON object
  66707. */
  66708. ShadowGenerator.prototype.serialize = function () {
  66709. var serializationObject = {};
  66710. var shadowMap = this.getShadowMap();
  66711. if (!shadowMap) {
  66712. return serializationObject;
  66713. }
  66714. serializationObject.lightId = this._light.id;
  66715. serializationObject.mapSize = shadowMap.getRenderSize();
  66716. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66717. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66718. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66719. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66720. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66721. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66722. serializationObject.depthScale = this.depthScale;
  66723. serializationObject.darkness = this.getDarkness();
  66724. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66725. serializationObject.blurKernel = this.blurKernel;
  66726. serializationObject.blurScale = this.blurScale;
  66727. serializationObject.useKernelBlur = this.useKernelBlur;
  66728. serializationObject.transparencyShadow = this._transparencyShadow;
  66729. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66730. serializationObject.bias = this.bias;
  66731. serializationObject.normalBias = this.normalBias;
  66732. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66733. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66734. serializationObject.filteringQuality = this.filteringQuality;
  66735. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66736. serializationObject.renderList = [];
  66737. if (shadowMap.renderList) {
  66738. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66739. var mesh = shadowMap.renderList[meshIndex];
  66740. serializationObject.renderList.push(mesh.id);
  66741. }
  66742. }
  66743. return serializationObject;
  66744. };
  66745. /**
  66746. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66747. * @param parsedShadowGenerator The JSON object to parse
  66748. * @param scene The scene to create the shadow map for
  66749. * @returns The parsed shadow generator
  66750. */
  66751. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66752. //casting to point light, as light is missing the position attr and typescript complains.
  66753. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66754. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66755. var shadowMap = shadowGenerator.getShadowMap();
  66756. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66757. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66758. meshes.forEach(function (mesh) {
  66759. if (!shadowMap) {
  66760. return;
  66761. }
  66762. if (!shadowMap.renderList) {
  66763. shadowMap.renderList = [];
  66764. }
  66765. shadowMap.renderList.push(mesh);
  66766. });
  66767. }
  66768. if (parsedShadowGenerator.usePoissonSampling) {
  66769. shadowGenerator.usePoissonSampling = true;
  66770. }
  66771. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66772. shadowGenerator.useExponentialShadowMap = true;
  66773. }
  66774. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66775. shadowGenerator.useBlurExponentialShadowMap = true;
  66776. }
  66777. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66778. shadowGenerator.useCloseExponentialShadowMap = true;
  66779. }
  66780. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66781. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66782. }
  66783. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66784. shadowGenerator.usePercentageCloserFiltering = true;
  66785. }
  66786. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66787. shadowGenerator.useContactHardeningShadow = true;
  66788. }
  66789. if (parsedShadowGenerator.filteringQuality) {
  66790. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66791. }
  66792. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66793. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66794. }
  66795. // Backward compat
  66796. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66797. shadowGenerator.useExponentialShadowMap = true;
  66798. }
  66799. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66800. shadowGenerator.useBlurExponentialShadowMap = true;
  66801. }
  66802. if (parsedShadowGenerator.depthScale) {
  66803. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66804. }
  66805. if (parsedShadowGenerator.blurScale) {
  66806. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66807. }
  66808. if (parsedShadowGenerator.blurBoxOffset) {
  66809. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66810. }
  66811. if (parsedShadowGenerator.useKernelBlur) {
  66812. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66813. }
  66814. if (parsedShadowGenerator.blurKernel) {
  66815. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66816. }
  66817. if (parsedShadowGenerator.bias !== undefined) {
  66818. shadowGenerator.bias = parsedShadowGenerator.bias;
  66819. }
  66820. if (parsedShadowGenerator.normalBias !== undefined) {
  66821. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66822. }
  66823. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66824. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66825. }
  66826. if (parsedShadowGenerator.darkness) {
  66827. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66828. }
  66829. if (parsedShadowGenerator.transparencyShadow) {
  66830. shadowGenerator.setTransparencyShadow(true);
  66831. }
  66832. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66833. return shadowGenerator;
  66834. };
  66835. /**
  66836. * Shadow generator mode None: no filtering applied.
  66837. */
  66838. ShadowGenerator.FILTER_NONE = 0;
  66839. /**
  66840. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66841. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66842. */
  66843. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66844. /**
  66845. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66846. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66847. */
  66848. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66849. /**
  66850. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66851. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66852. */
  66853. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66854. /**
  66855. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66856. * edge artifacts on steep falloff.
  66857. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66858. */
  66859. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66860. /**
  66861. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66862. * edge artifacts on steep falloff.
  66863. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66864. */
  66865. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66866. /**
  66867. * Shadow generator mode PCF: Percentage Closer Filtering
  66868. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66869. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66870. */
  66871. ShadowGenerator.FILTER_PCF = 6;
  66872. /**
  66873. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66874. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66875. * Contact Hardening
  66876. */
  66877. ShadowGenerator.FILTER_PCSS = 7;
  66878. /**
  66879. * Reserved for PCF and PCSS
  66880. * Highest Quality.
  66881. *
  66882. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66883. *
  66884. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66885. */
  66886. ShadowGenerator.QUALITY_HIGH = 0;
  66887. /**
  66888. * Reserved for PCF and PCSS
  66889. * Good tradeoff for quality/perf cross devices
  66890. *
  66891. * Execute PCF on a 3*3 kernel.
  66892. *
  66893. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66894. */
  66895. ShadowGenerator.QUALITY_MEDIUM = 1;
  66896. /**
  66897. * Reserved for PCF and PCSS
  66898. * The lowest quality but the fastest.
  66899. *
  66900. * Execute PCF on a 1*1 kernel.
  66901. *
  66902. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66903. */
  66904. ShadowGenerator.QUALITY_LOW = 2;
  66905. return ShadowGenerator;
  66906. }());
  66907. BABYLON.ShadowGenerator = ShadowGenerator;
  66908. })(BABYLON || (BABYLON = {}));
  66909. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66910. var BABYLON;
  66911. (function (BABYLON) {
  66912. var DefaultLoadingScreen = /** @class */ (function () {
  66913. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66914. if (_loadingText === void 0) { _loadingText = ""; }
  66915. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66916. var _this = this;
  66917. this._renderingCanvas = _renderingCanvas;
  66918. this._loadingText = _loadingText;
  66919. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66920. // Resize
  66921. this._resizeLoadingUI = function () {
  66922. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66923. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66924. if (!_this._loadingDiv) {
  66925. return;
  66926. }
  66927. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66928. _this._loadingDiv.style.left = canvasRect.left + "px";
  66929. _this._loadingDiv.style.top = canvasRect.top + "px";
  66930. _this._loadingDiv.style.width = canvasRect.width + "px";
  66931. _this._loadingDiv.style.height = canvasRect.height + "px";
  66932. };
  66933. }
  66934. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66935. if (this._loadingDiv) {
  66936. // Do not add a loading screen if there is already one
  66937. return;
  66938. }
  66939. this._loadingDiv = document.createElement("div");
  66940. this._loadingDiv.id = "babylonjsLoadingDiv";
  66941. this._loadingDiv.style.opacity = "0";
  66942. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66943. this._loadingDiv.style.pointerEvents = "none";
  66944. // Loading text
  66945. this._loadingTextDiv = document.createElement("div");
  66946. this._loadingTextDiv.style.position = "absolute";
  66947. this._loadingTextDiv.style.left = "0";
  66948. this._loadingTextDiv.style.top = "50%";
  66949. this._loadingTextDiv.style.marginTop = "80px";
  66950. this._loadingTextDiv.style.width = "100%";
  66951. this._loadingTextDiv.style.height = "20px";
  66952. this._loadingTextDiv.style.fontFamily = "Arial";
  66953. this._loadingTextDiv.style.fontSize = "14px";
  66954. this._loadingTextDiv.style.color = "white";
  66955. this._loadingTextDiv.style.textAlign = "center";
  66956. this._loadingTextDiv.innerHTML = "Loading";
  66957. this._loadingDiv.appendChild(this._loadingTextDiv);
  66958. //set the predefined text
  66959. this._loadingTextDiv.innerHTML = this._loadingText;
  66960. // Generating keyframes
  66961. var style = document.createElement('style');
  66962. style.type = 'text/css';
  66963. 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 }";
  66964. style.innerHTML = keyFrames;
  66965. document.getElementsByTagName('head')[0].appendChild(style);
  66966. // Loading img
  66967. var imgBack = new Image();
  66968. 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";
  66969. imgBack.style.position = "absolute";
  66970. imgBack.style.left = "50%";
  66971. imgBack.style.top = "50%";
  66972. imgBack.style.marginLeft = "-60px";
  66973. imgBack.style.marginTop = "-60px";
  66974. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66975. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66976. imgBack.style.transformOrigin = "50% 50%";
  66977. imgBack.style.webkitTransformOrigin = "50% 50%";
  66978. this._loadingDiv.appendChild(imgBack);
  66979. this._resizeLoadingUI();
  66980. window.addEventListener("resize", this._resizeLoadingUI);
  66981. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66982. document.body.appendChild(this._loadingDiv);
  66983. this._loadingDiv.style.opacity = "1";
  66984. };
  66985. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66986. var _this = this;
  66987. if (!this._loadingDiv) {
  66988. return;
  66989. }
  66990. var onTransitionEnd = function () {
  66991. if (!_this._loadingDiv) {
  66992. return;
  66993. }
  66994. document.body.removeChild(_this._loadingDiv);
  66995. window.removeEventListener("resize", _this._resizeLoadingUI);
  66996. _this._loadingDiv = null;
  66997. };
  66998. this._loadingDiv.style.opacity = "0";
  66999. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67000. };
  67001. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67002. set: function (text) {
  67003. this._loadingText = text;
  67004. if (this._loadingTextDiv) {
  67005. this._loadingTextDiv.innerHTML = this._loadingText;
  67006. }
  67007. },
  67008. enumerable: true,
  67009. configurable: true
  67010. });
  67011. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67012. get: function () {
  67013. return this._loadingDivBackgroundColor;
  67014. },
  67015. set: function (color) {
  67016. this._loadingDivBackgroundColor = color;
  67017. if (!this._loadingDiv) {
  67018. return;
  67019. }
  67020. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67021. },
  67022. enumerable: true,
  67023. configurable: true
  67024. });
  67025. return DefaultLoadingScreen;
  67026. }());
  67027. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67028. })(BABYLON || (BABYLON = {}));
  67029. //# sourceMappingURL=babylon.loadingScreen.js.map
  67030. var BABYLON;
  67031. (function (BABYLON) {
  67032. var SceneLoaderProgressEvent = /** @class */ (function () {
  67033. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67034. this.lengthComputable = lengthComputable;
  67035. this.loaded = loaded;
  67036. this.total = total;
  67037. }
  67038. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67039. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67040. };
  67041. return SceneLoaderProgressEvent;
  67042. }());
  67043. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67044. var SceneLoader = /** @class */ (function () {
  67045. function SceneLoader() {
  67046. }
  67047. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67048. get: function () {
  67049. return 0;
  67050. },
  67051. enumerable: true,
  67052. configurable: true
  67053. });
  67054. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67055. get: function () {
  67056. return 1;
  67057. },
  67058. enumerable: true,
  67059. configurable: true
  67060. });
  67061. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67062. get: function () {
  67063. return 2;
  67064. },
  67065. enumerable: true,
  67066. configurable: true
  67067. });
  67068. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67069. get: function () {
  67070. return 3;
  67071. },
  67072. enumerable: true,
  67073. configurable: true
  67074. });
  67075. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67076. get: function () {
  67077. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67078. },
  67079. set: function (value) {
  67080. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67081. },
  67082. enumerable: true,
  67083. configurable: true
  67084. });
  67085. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67086. get: function () {
  67087. return SceneLoader._ShowLoadingScreen;
  67088. },
  67089. set: function (value) {
  67090. SceneLoader._ShowLoadingScreen = value;
  67091. },
  67092. enumerable: true,
  67093. configurable: true
  67094. });
  67095. Object.defineProperty(SceneLoader, "loggingLevel", {
  67096. get: function () {
  67097. return SceneLoader._loggingLevel;
  67098. },
  67099. set: function (value) {
  67100. SceneLoader._loggingLevel = value;
  67101. },
  67102. enumerable: true,
  67103. configurable: true
  67104. });
  67105. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67106. get: function () {
  67107. return SceneLoader._CleanBoneMatrixWeights;
  67108. },
  67109. set: function (value) {
  67110. SceneLoader._CleanBoneMatrixWeights = value;
  67111. },
  67112. enumerable: true,
  67113. configurable: true
  67114. });
  67115. SceneLoader._getDefaultPlugin = function () {
  67116. return SceneLoader._registeredPlugins[".babylon"];
  67117. };
  67118. SceneLoader._getPluginForExtension = function (extension) {
  67119. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67120. if (registeredPlugin) {
  67121. return registeredPlugin;
  67122. }
  67123. 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");
  67124. return SceneLoader._getDefaultPlugin();
  67125. };
  67126. SceneLoader._getPluginForDirectLoad = function (data) {
  67127. for (var extension in SceneLoader._registeredPlugins) {
  67128. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67129. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67130. return SceneLoader._registeredPlugins[extension];
  67131. }
  67132. }
  67133. return SceneLoader._getDefaultPlugin();
  67134. };
  67135. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67136. if (sceneFilename.name) {
  67137. sceneFilename = sceneFilename.name;
  67138. }
  67139. var queryStringPosition = sceneFilename.indexOf("?");
  67140. if (queryStringPosition !== -1) {
  67141. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67142. }
  67143. var dotPosition = sceneFilename.lastIndexOf(".");
  67144. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67145. return SceneLoader._getPluginForExtension(extension);
  67146. };
  67147. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67148. SceneLoader._getDirectLoad = function (sceneFilename) {
  67149. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67150. return sceneFilename.substr(5);
  67151. }
  67152. return null;
  67153. };
  67154. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67155. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67156. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67157. var plugin;
  67158. if (registeredPlugin.plugin.createPlugin) {
  67159. plugin = registeredPlugin.plugin.createPlugin();
  67160. }
  67161. else {
  67162. plugin = registeredPlugin.plugin;
  67163. }
  67164. var useArrayBuffer = registeredPlugin.isBinary;
  67165. var database;
  67166. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67167. var dataCallback = function (data, responseURL) {
  67168. if (scene.isDisposed) {
  67169. onError("Scene has been disposed");
  67170. return;
  67171. }
  67172. scene.database = database;
  67173. onSuccess(plugin, data, responseURL);
  67174. };
  67175. var request = null;
  67176. var pluginDisposed = false;
  67177. var onDisposeObservable = plugin.onDisposeObservable;
  67178. if (onDisposeObservable) {
  67179. onDisposeObservable.add(function () {
  67180. pluginDisposed = true;
  67181. if (request) {
  67182. request.abort();
  67183. request = null;
  67184. }
  67185. onDispose();
  67186. });
  67187. }
  67188. var manifestChecked = function () {
  67189. if (pluginDisposed) {
  67190. return;
  67191. }
  67192. var url = rootUrl + sceneFilename;
  67193. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67194. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67195. } : undefined, database, useArrayBuffer, function (request, exception) {
  67196. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67197. });
  67198. };
  67199. if (directLoad) {
  67200. dataCallback(directLoad);
  67201. return plugin;
  67202. }
  67203. if (rootUrl.indexOf("file:") === -1) {
  67204. var engine = scene.getEngine();
  67205. var canUseOfflineSupport = engine.enableOfflineSupport;
  67206. if (canUseOfflineSupport) {
  67207. // Also check for exceptions
  67208. var exceptionFound = false;
  67209. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67210. var regex = _a[_i];
  67211. if (regex.test(rootUrl + sceneFilename)) {
  67212. exceptionFound = true;
  67213. break;
  67214. }
  67215. }
  67216. canUseOfflineSupport = !exceptionFound;
  67217. }
  67218. if (canUseOfflineSupport) {
  67219. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67220. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67221. }
  67222. else {
  67223. manifestChecked();
  67224. }
  67225. }
  67226. // Loading file from disk via input file or drag'n'drop
  67227. else {
  67228. var fileOrString = sceneFilename;
  67229. if (fileOrString.name) { // File
  67230. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67231. }
  67232. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67233. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67234. }
  67235. else {
  67236. onError("Unable to find file named " + sceneFilename);
  67237. }
  67238. }
  67239. return plugin;
  67240. };
  67241. // Public functions
  67242. SceneLoader.GetPluginForExtension = function (extension) {
  67243. return SceneLoader._getPluginForExtension(extension).plugin;
  67244. };
  67245. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67246. return !!SceneLoader._registeredPlugins[extension];
  67247. };
  67248. SceneLoader.RegisterPlugin = function (plugin) {
  67249. if (typeof plugin.extensions === "string") {
  67250. var extension = plugin.extensions;
  67251. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67252. plugin: plugin,
  67253. isBinary: false
  67254. };
  67255. }
  67256. else {
  67257. var extensions = plugin.extensions;
  67258. Object.keys(extensions).forEach(function (extension) {
  67259. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67260. plugin: plugin,
  67261. isBinary: extensions[extension].isBinary
  67262. };
  67263. });
  67264. }
  67265. };
  67266. /**
  67267. * Import meshes into a scene
  67268. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67269. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67270. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67271. * @param scene the instance of BABYLON.Scene to append to
  67272. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67273. * @param onProgress a callback with a progress event for each file being loaded
  67274. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67275. * @param pluginExtension the extension used to determine the plugin
  67276. * @returns The loaded plugin
  67277. */
  67278. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67279. if (sceneFilename === void 0) { sceneFilename = ""; }
  67280. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67281. if (onSuccess === void 0) { onSuccess = null; }
  67282. if (onProgress === void 0) { onProgress = null; }
  67283. if (onError === void 0) { onError = null; }
  67284. if (pluginExtension === void 0) { pluginExtension = null; }
  67285. if (!scene) {
  67286. BABYLON.Tools.Error("No scene available to import mesh to");
  67287. return null;
  67288. }
  67289. if (!sceneFilename) {
  67290. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67291. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67292. }
  67293. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67294. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67295. return null;
  67296. }
  67297. var loadingToken = {};
  67298. scene._addPendingData(loadingToken);
  67299. var disposeHandler = function () {
  67300. scene._removePendingData(loadingToken);
  67301. };
  67302. var errorHandler = function (message, exception) {
  67303. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67304. if (onError) {
  67305. onError(scene, errorMessage, exception);
  67306. }
  67307. else {
  67308. BABYLON.Tools.Error(errorMessage);
  67309. // should the exception be thrown?
  67310. }
  67311. disposeHandler();
  67312. };
  67313. var progressHandler = onProgress ? function (event) {
  67314. try {
  67315. onProgress(event);
  67316. }
  67317. catch (e) {
  67318. errorHandler("Error in onProgress callback", e);
  67319. }
  67320. } : undefined;
  67321. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67322. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67323. if (onSuccess) {
  67324. try {
  67325. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67326. }
  67327. catch (e) {
  67328. errorHandler("Error in onSuccess callback", e);
  67329. }
  67330. }
  67331. scene._removePendingData(loadingToken);
  67332. };
  67333. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67334. if (plugin.rewriteRootURL) {
  67335. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67336. }
  67337. if (sceneFilename === "") {
  67338. if (sceneFilename === "") {
  67339. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67340. }
  67341. }
  67342. if (plugin.importMesh) {
  67343. var syncedPlugin = plugin;
  67344. var meshes = new Array();
  67345. var particleSystems = new Array();
  67346. var skeletons = new Array();
  67347. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67348. return;
  67349. }
  67350. scene.loadingPluginName = plugin.name;
  67351. successHandler(meshes, particleSystems, skeletons, []);
  67352. }
  67353. else {
  67354. var asyncedPlugin = plugin;
  67355. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67356. scene.loadingPluginName = plugin.name;
  67357. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67358. }).catch(function (error) {
  67359. errorHandler(error.message, error);
  67360. });
  67361. }
  67362. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67363. };
  67364. /**
  67365. * Import meshes into a scene
  67366. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67367. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67368. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67369. * @param scene the instance of BABYLON.Scene to append to
  67370. * @param onProgress a callback with a progress event for each file being loaded
  67371. * @param pluginExtension the extension used to determine the plugin
  67372. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67373. */
  67374. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67375. if (sceneFilename === void 0) { sceneFilename = ""; }
  67376. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67377. if (onProgress === void 0) { onProgress = null; }
  67378. if (pluginExtension === void 0) { pluginExtension = null; }
  67379. return new Promise(function (resolve, reject) {
  67380. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67381. resolve({
  67382. meshes: meshes,
  67383. particleSystems: particleSystems,
  67384. skeletons: skeletons,
  67385. animationGroups: animationGroups
  67386. });
  67387. }, onProgress, function (scene, message, exception) {
  67388. reject(exception || new Error(message));
  67389. }, pluginExtension);
  67390. });
  67391. };
  67392. /**
  67393. * Load a scene
  67394. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67395. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67396. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67397. * @param onSuccess a callback with the scene when import succeeds
  67398. * @param onProgress a callback with a progress event for each file being loaded
  67399. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67400. * @param pluginExtension the extension used to determine the plugin
  67401. * @returns The loaded plugin
  67402. */
  67403. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67404. if (onSuccess === void 0) { onSuccess = null; }
  67405. if (onProgress === void 0) { onProgress = null; }
  67406. if (onError === void 0) { onError = null; }
  67407. if (pluginExtension === void 0) { pluginExtension = null; }
  67408. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67409. };
  67410. /**
  67411. * Load a scene
  67412. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67413. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67414. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67415. * @param onProgress a callback with a progress event for each file being loaded
  67416. * @param pluginExtension the extension used to determine the plugin
  67417. * @returns The loaded scene
  67418. */
  67419. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67420. if (onProgress === void 0) { onProgress = null; }
  67421. if (pluginExtension === void 0) { pluginExtension = null; }
  67422. return new Promise(function (resolve, reject) {
  67423. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67424. resolve(scene);
  67425. }, onProgress, function (scene, message, exception) {
  67426. reject(exception || new Error(message));
  67427. }, pluginExtension);
  67428. });
  67429. };
  67430. /**
  67431. * Append a scene
  67432. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67433. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67434. * @param scene is the instance of BABYLON.Scene to append to
  67435. * @param onSuccess a callback with the scene when import succeeds
  67436. * @param onProgress a callback with a progress event for each file being loaded
  67437. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67438. * @param pluginExtension the extension used to determine the plugin
  67439. * @returns The loaded plugin
  67440. */
  67441. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67442. if (sceneFilename === void 0) { sceneFilename = ""; }
  67443. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67444. if (onSuccess === void 0) { onSuccess = null; }
  67445. if (onProgress === void 0) { onProgress = null; }
  67446. if (onError === void 0) { onError = null; }
  67447. if (pluginExtension === void 0) { pluginExtension = null; }
  67448. if (!scene) {
  67449. BABYLON.Tools.Error("No scene available to append to");
  67450. return null;
  67451. }
  67452. if (!sceneFilename) {
  67453. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67454. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67455. }
  67456. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67457. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67458. return null;
  67459. }
  67460. if (SceneLoader.ShowLoadingScreen) {
  67461. scene.getEngine().displayLoadingUI();
  67462. }
  67463. var loadingToken = {};
  67464. scene._addPendingData(loadingToken);
  67465. var disposeHandler = function () {
  67466. scene._removePendingData(loadingToken);
  67467. scene.getEngine().hideLoadingUI();
  67468. };
  67469. var errorHandler = function (message, exception) {
  67470. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67471. if (onError) {
  67472. onError(scene, errorMessage, exception);
  67473. }
  67474. else {
  67475. BABYLON.Tools.Error(errorMessage);
  67476. // should the exception be thrown?
  67477. }
  67478. disposeHandler();
  67479. };
  67480. var progressHandler = onProgress ? function (event) {
  67481. try {
  67482. onProgress(event);
  67483. }
  67484. catch (e) {
  67485. errorHandler("Error in onProgress callback", e);
  67486. }
  67487. } : undefined;
  67488. var successHandler = function () {
  67489. if (onSuccess) {
  67490. try {
  67491. onSuccess(scene);
  67492. }
  67493. catch (e) {
  67494. errorHandler("Error in onSuccess callback", e);
  67495. }
  67496. }
  67497. scene._removePendingData(loadingToken);
  67498. };
  67499. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67500. if (sceneFilename === "") {
  67501. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67502. }
  67503. if (plugin.load) {
  67504. var syncedPlugin = plugin;
  67505. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67506. return;
  67507. }
  67508. scene.loadingPluginName = plugin.name;
  67509. successHandler();
  67510. }
  67511. else {
  67512. var asyncedPlugin = plugin;
  67513. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67514. scene.loadingPluginName = plugin.name;
  67515. successHandler();
  67516. }).catch(function (error) {
  67517. errorHandler(error.message, error);
  67518. });
  67519. }
  67520. if (SceneLoader.ShowLoadingScreen) {
  67521. scene.executeWhenReady(function () {
  67522. scene.getEngine().hideLoadingUI();
  67523. });
  67524. }
  67525. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67526. };
  67527. /**
  67528. * Append a scene
  67529. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67530. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67531. * @param scene is the instance of BABYLON.Scene to append to
  67532. * @param onProgress a callback with a progress event for each file being loaded
  67533. * @param pluginExtension the extension used to determine the plugin
  67534. * @returns The given scene
  67535. */
  67536. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67537. if (sceneFilename === void 0) { sceneFilename = ""; }
  67538. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67539. if (onProgress === void 0) { onProgress = null; }
  67540. if (pluginExtension === void 0) { pluginExtension = null; }
  67541. return new Promise(function (resolve, reject) {
  67542. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67543. resolve(scene);
  67544. }, onProgress, function (scene, message, exception) {
  67545. reject(exception || new Error(message));
  67546. }, pluginExtension);
  67547. });
  67548. };
  67549. /**
  67550. * Load a scene into an asset container
  67551. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67552. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67553. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67554. * @param onSuccess a callback with the scene when import succeeds
  67555. * @param onProgress a callback with a progress event for each file being loaded
  67556. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67557. * @param pluginExtension the extension used to determine the plugin
  67558. * @returns The loaded plugin
  67559. */
  67560. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67561. if (sceneFilename === void 0) { sceneFilename = ""; }
  67562. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67563. if (onSuccess === void 0) { onSuccess = null; }
  67564. if (onProgress === void 0) { onProgress = null; }
  67565. if (onError === void 0) { onError = null; }
  67566. if (pluginExtension === void 0) { pluginExtension = null; }
  67567. if (!scene) {
  67568. BABYLON.Tools.Error("No scene available to load asset container to");
  67569. return null;
  67570. }
  67571. if (!sceneFilename) {
  67572. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67573. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67574. }
  67575. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67576. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67577. return null;
  67578. }
  67579. var loadingToken = {};
  67580. scene._addPendingData(loadingToken);
  67581. var disposeHandler = function () {
  67582. scene._removePendingData(loadingToken);
  67583. };
  67584. var errorHandler = function (message, exception) {
  67585. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67586. if (onError) {
  67587. onError(scene, errorMessage, exception);
  67588. }
  67589. else {
  67590. BABYLON.Tools.Error(errorMessage);
  67591. // should the exception be thrown?
  67592. }
  67593. disposeHandler();
  67594. };
  67595. var progressHandler = onProgress ? function (event) {
  67596. try {
  67597. onProgress(event);
  67598. }
  67599. catch (e) {
  67600. errorHandler("Error in onProgress callback", e);
  67601. }
  67602. } : undefined;
  67603. var successHandler = function (assets) {
  67604. if (onSuccess) {
  67605. try {
  67606. onSuccess(assets);
  67607. }
  67608. catch (e) {
  67609. errorHandler("Error in onSuccess callback", e);
  67610. }
  67611. }
  67612. scene._removePendingData(loadingToken);
  67613. };
  67614. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67615. if (plugin.loadAssetContainer) {
  67616. var syncedPlugin = plugin;
  67617. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67618. if (!assetContainer) {
  67619. return;
  67620. }
  67621. scene.loadingPluginName = plugin.name;
  67622. successHandler(assetContainer);
  67623. }
  67624. else if (plugin.loadAssetContainerAsync) {
  67625. var asyncedPlugin = plugin;
  67626. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67627. scene.loadingPluginName = plugin.name;
  67628. successHandler(assetContainer);
  67629. }).catch(function (error) {
  67630. errorHandler(error.message, error);
  67631. });
  67632. }
  67633. else {
  67634. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67635. }
  67636. if (SceneLoader.ShowLoadingScreen) {
  67637. scene.executeWhenReady(function () {
  67638. scene.getEngine().hideLoadingUI();
  67639. });
  67640. }
  67641. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67642. };
  67643. /**
  67644. * Load a scene into an asset container
  67645. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67646. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67647. * @param scene is the instance of BABYLON.Scene to append to
  67648. * @param onProgress a callback with a progress event for each file being loaded
  67649. * @param pluginExtension the extension used to determine the plugin
  67650. * @returns The loaded asset container
  67651. */
  67652. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67653. if (sceneFilename === void 0) { sceneFilename = ""; }
  67654. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67655. if (onProgress === void 0) { onProgress = null; }
  67656. if (pluginExtension === void 0) { pluginExtension = null; }
  67657. return new Promise(function (resolve, reject) {
  67658. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67659. resolve(assetContainer);
  67660. }, onProgress, function (scene, message, exception) {
  67661. reject(exception || new Error(message));
  67662. }, pluginExtension);
  67663. });
  67664. };
  67665. // Flags
  67666. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67667. SceneLoader._ShowLoadingScreen = true;
  67668. SceneLoader._CleanBoneMatrixWeights = false;
  67669. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67670. // Members
  67671. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67672. SceneLoader._registeredPlugins = {};
  67673. return SceneLoader;
  67674. }());
  67675. BABYLON.SceneLoader = SceneLoader;
  67676. ;
  67677. })(BABYLON || (BABYLON = {}));
  67678. //# sourceMappingURL=babylon.sceneLoader.js.map
  67679. var BABYLON;
  67680. (function (BABYLON) {
  67681. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67682. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67683. var parsedMaterial = parsedData.materials[index];
  67684. if (parsedMaterial.id === id) {
  67685. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67686. }
  67687. }
  67688. return null;
  67689. };
  67690. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67691. for (var i in names) {
  67692. if (mesh.name === names[i]) {
  67693. hierarchyIds.push(mesh.id);
  67694. return true;
  67695. }
  67696. }
  67697. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67698. hierarchyIds.push(mesh.id);
  67699. return true;
  67700. }
  67701. return false;
  67702. };
  67703. var logOperation = function (operation, producer) {
  67704. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67705. };
  67706. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67707. if (addToScene === void 0) { addToScene = false; }
  67708. var container = new BABYLON.AssetContainer(scene);
  67709. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67710. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67711. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67712. // and avoid problems with multiple concurrent .babylon loads.
  67713. var log = "importScene has failed JSON parse";
  67714. try {
  67715. var parsedData = JSON.parse(data);
  67716. log = "";
  67717. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67718. var index;
  67719. var cache;
  67720. // Lights
  67721. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67722. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67723. var parsedLight = parsedData.lights[index];
  67724. var light = BABYLON.Light.Parse(parsedLight, scene);
  67725. if (light) {
  67726. container.lights.push(light);
  67727. log += (index === 0 ? "\n\tLights:" : "");
  67728. log += "\n\t\t" + light.toString(fullDetails);
  67729. }
  67730. }
  67731. }
  67732. // Animations
  67733. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67734. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67735. var parsedAnimation = parsedData.animations[index];
  67736. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67737. scene.animations.push(animation);
  67738. container.animations.push(animation);
  67739. log += (index === 0 ? "\n\tAnimations:" : "");
  67740. log += "\n\t\t" + animation.toString(fullDetails);
  67741. }
  67742. }
  67743. // Materials
  67744. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67745. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67746. var parsedMaterial = parsedData.materials[index];
  67747. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67748. container.materials.push(mat);
  67749. log += (index === 0 ? "\n\tMaterials:" : "");
  67750. log += "\n\t\t" + mat.toString(fullDetails);
  67751. }
  67752. }
  67753. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67754. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67755. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67756. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67757. container.multiMaterials.push(mmat);
  67758. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67759. log += "\n\t\t" + mmat.toString(fullDetails);
  67760. }
  67761. }
  67762. // Morph targets
  67763. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67764. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67765. var managerData = _a[_i];
  67766. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67767. }
  67768. }
  67769. // Skeletons
  67770. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67771. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67772. var parsedSkeleton = parsedData.skeletons[index];
  67773. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67774. container.skeletons.push(skeleton);
  67775. log += (index === 0 ? "\n\tSkeletons:" : "");
  67776. log += "\n\t\t" + skeleton.toString(fullDetails);
  67777. }
  67778. }
  67779. // Geometries
  67780. var geometries = parsedData.geometries;
  67781. if (geometries !== undefined && geometries !== null) {
  67782. var addedGeometry = new Array();
  67783. // Boxes
  67784. var boxes = geometries.boxes;
  67785. if (boxes !== undefined && boxes !== null) {
  67786. for (index = 0, cache = boxes.length; index < cache; index++) {
  67787. var parsedBox = boxes[index];
  67788. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67789. }
  67790. }
  67791. // Spheres
  67792. var spheres = geometries.spheres;
  67793. if (spheres !== undefined && spheres !== null) {
  67794. for (index = 0, cache = spheres.length; index < cache; index++) {
  67795. var parsedSphere = spheres[index];
  67796. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67797. }
  67798. }
  67799. // Cylinders
  67800. var cylinders = geometries.cylinders;
  67801. if (cylinders !== undefined && cylinders !== null) {
  67802. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67803. var parsedCylinder = cylinders[index];
  67804. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67805. }
  67806. }
  67807. // Toruses
  67808. var toruses = geometries.toruses;
  67809. if (toruses !== undefined && toruses !== null) {
  67810. for (index = 0, cache = toruses.length; index < cache; index++) {
  67811. var parsedTorus = toruses[index];
  67812. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67813. }
  67814. }
  67815. // Grounds
  67816. var grounds = geometries.grounds;
  67817. if (grounds !== undefined && grounds !== null) {
  67818. for (index = 0, cache = grounds.length; index < cache; index++) {
  67819. var parsedGround = grounds[index];
  67820. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67821. }
  67822. }
  67823. // Planes
  67824. var planes = geometries.planes;
  67825. if (planes !== undefined && planes !== null) {
  67826. for (index = 0, cache = planes.length; index < cache; index++) {
  67827. var parsedPlane = planes[index];
  67828. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67829. }
  67830. }
  67831. // TorusKnots
  67832. var torusKnots = geometries.torusKnots;
  67833. if (torusKnots !== undefined && torusKnots !== null) {
  67834. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67835. var parsedTorusKnot = torusKnots[index];
  67836. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67837. }
  67838. }
  67839. // VertexData
  67840. var vertexData = geometries.vertexData;
  67841. if (vertexData !== undefined && vertexData !== null) {
  67842. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67843. var parsedVertexData = vertexData[index];
  67844. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67845. }
  67846. }
  67847. addedGeometry.forEach(function (g) {
  67848. if (g) {
  67849. container.geometries.push(g);
  67850. }
  67851. });
  67852. }
  67853. // Transform nodes
  67854. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67855. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67856. var parsedTransformNode = parsedData.transformNodes[index];
  67857. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67858. container.transformNodes.push(node);
  67859. }
  67860. }
  67861. // Meshes
  67862. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67863. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67864. var parsedMesh = parsedData.meshes[index];
  67865. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67866. container.meshes.push(mesh);
  67867. log += (index === 0 ? "\n\tMeshes:" : "");
  67868. log += "\n\t\t" + mesh.toString(fullDetails);
  67869. }
  67870. }
  67871. // Cameras
  67872. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67873. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67874. var parsedCamera = parsedData.cameras[index];
  67875. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67876. container.cameras.push(camera);
  67877. log += (index === 0 ? "\n\tCameras:" : "");
  67878. log += "\n\t\t" + camera.toString(fullDetails);
  67879. }
  67880. }
  67881. // Browsing all the graph to connect the dots
  67882. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67883. var camera = scene.cameras[index];
  67884. if (camera._waitingParentId) {
  67885. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67886. camera._waitingParentId = null;
  67887. }
  67888. }
  67889. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67890. var light_1 = scene.lights[index];
  67891. if (light_1 && light_1._waitingParentId) {
  67892. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67893. light_1._waitingParentId = null;
  67894. }
  67895. }
  67896. // Sounds
  67897. // TODO: add sound
  67898. var loadedSounds = [];
  67899. var loadedSound;
  67900. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67901. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67902. var parsedSound = parsedData.sounds[index];
  67903. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67904. if (!parsedSound.url)
  67905. parsedSound.url = parsedSound.name;
  67906. if (!loadedSounds[parsedSound.url]) {
  67907. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67908. loadedSounds[parsedSound.url] = loadedSound;
  67909. container.sounds.push(loadedSound);
  67910. }
  67911. else {
  67912. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67913. }
  67914. }
  67915. else {
  67916. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67917. }
  67918. }
  67919. }
  67920. loadedSounds = [];
  67921. // Connect parents & children and parse actions
  67922. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67923. var transformNode = scene.transformNodes[index];
  67924. if (transformNode._waitingParentId) {
  67925. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67926. transformNode._waitingParentId = null;
  67927. }
  67928. }
  67929. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67930. var mesh = scene.meshes[index];
  67931. if (mesh._waitingParentId) {
  67932. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67933. mesh._waitingParentId = null;
  67934. }
  67935. if (mesh._waitingActions) {
  67936. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67937. mesh._waitingActions = null;
  67938. }
  67939. }
  67940. // freeze world matrix application
  67941. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67942. var currentMesh = scene.meshes[index];
  67943. if (currentMesh._waitingFreezeWorldMatrix) {
  67944. currentMesh.freezeWorldMatrix();
  67945. currentMesh._waitingFreezeWorldMatrix = null;
  67946. }
  67947. else {
  67948. currentMesh.computeWorldMatrix(true);
  67949. }
  67950. }
  67951. // Particles Systems
  67952. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67953. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67954. var parsedParticleSystem = parsedData.particleSystems[index];
  67955. if (parsedParticleSystem.activeParticleCount) {
  67956. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67957. container.particleSystems.push(ps);
  67958. }
  67959. else {
  67960. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67961. container.particleSystems.push(ps);
  67962. }
  67963. }
  67964. }
  67965. // Lens flares
  67966. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67967. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67968. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67969. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67970. container.lensFlareSystems.push(lf);
  67971. }
  67972. }
  67973. // Shadows
  67974. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67975. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67976. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67977. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67978. container.shadowGenerators.push(sg);
  67979. }
  67980. }
  67981. // Lights exclusions / inclusions
  67982. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67983. var light_2 = scene.lights[index];
  67984. // Excluded check
  67985. if (light_2._excludedMeshesIds.length > 0) {
  67986. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67987. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67988. if (excludedMesh) {
  67989. light_2.excludedMeshes.push(excludedMesh);
  67990. }
  67991. }
  67992. light_2._excludedMeshesIds = [];
  67993. }
  67994. // Included check
  67995. if (light_2._includedOnlyMeshesIds.length > 0) {
  67996. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67997. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67998. if (includedOnlyMesh) {
  67999. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68000. }
  68001. }
  68002. light_2._includedOnlyMeshesIds = [];
  68003. }
  68004. }
  68005. // Effect layers
  68006. if (parsedData.effectLayers) {
  68007. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68008. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68009. container.effectLayers.push(effectLayer);
  68010. }
  68011. }
  68012. // Actions (scene)
  68013. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68014. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68015. }
  68016. if (!addToScene) {
  68017. container.removeAllFromScene();
  68018. }
  68019. }
  68020. catch (err) {
  68021. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68022. if (onError) {
  68023. onError(msg, err);
  68024. }
  68025. else {
  68026. BABYLON.Tools.Log(msg);
  68027. throw err;
  68028. }
  68029. }
  68030. finally {
  68031. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68032. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68033. }
  68034. }
  68035. return container;
  68036. };
  68037. BABYLON.SceneLoader.RegisterPlugin({
  68038. name: "babylon.js",
  68039. extensions: ".babylon",
  68040. canDirectLoad: function (data) {
  68041. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68042. return true;
  68043. }
  68044. return false;
  68045. },
  68046. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68047. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68048. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68049. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68050. // and avoid problems with multiple concurrent .babylon loads.
  68051. var log = "importMesh has failed JSON parse";
  68052. try {
  68053. var parsedData = JSON.parse(data);
  68054. log = "";
  68055. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68056. if (!meshesNames) {
  68057. meshesNames = null;
  68058. }
  68059. else if (!Array.isArray(meshesNames)) {
  68060. meshesNames = [meshesNames];
  68061. }
  68062. var hierarchyIds = new Array();
  68063. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68064. var loadedSkeletonsIds = [];
  68065. var loadedMaterialsIds = [];
  68066. var index;
  68067. var cache;
  68068. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68069. var parsedMesh = parsedData.meshes[index];
  68070. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68071. if (meshesNames !== null) {
  68072. // Remove found mesh name from list.
  68073. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68074. }
  68075. //Geometry?
  68076. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68077. //does the file contain geometries?
  68078. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68079. //find the correct geometry and add it to the scene
  68080. var found = false;
  68081. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68082. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68083. return;
  68084. }
  68085. else {
  68086. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68087. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68088. switch (geometryType) {
  68089. case "boxes":
  68090. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68091. break;
  68092. case "spheres":
  68093. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68094. break;
  68095. case "cylinders":
  68096. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68097. break;
  68098. case "toruses":
  68099. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68100. break;
  68101. case "grounds":
  68102. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68103. break;
  68104. case "planes":
  68105. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68106. break;
  68107. case "torusKnots":
  68108. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68109. break;
  68110. case "vertexData":
  68111. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68112. break;
  68113. }
  68114. found = true;
  68115. }
  68116. });
  68117. }
  68118. });
  68119. if (found === false) {
  68120. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68121. }
  68122. }
  68123. }
  68124. // Material ?
  68125. if (parsedMesh.materialId) {
  68126. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68127. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68128. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68129. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68130. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68131. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68132. var subMatId = parsedMultiMaterial.materials[matIndex];
  68133. loadedMaterialsIds.push(subMatId);
  68134. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68135. if (mat) {
  68136. log += "\n\tMaterial " + mat.toString(fullDetails);
  68137. }
  68138. }
  68139. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68140. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68141. if (mmat) {
  68142. materialFound = true;
  68143. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68144. }
  68145. break;
  68146. }
  68147. }
  68148. }
  68149. if (materialFound === false) {
  68150. loadedMaterialsIds.push(parsedMesh.materialId);
  68151. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68152. if (!mat) {
  68153. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68154. }
  68155. else {
  68156. log += "\n\tMaterial " + mat.toString(fullDetails);
  68157. }
  68158. }
  68159. }
  68160. // Skeleton ?
  68161. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68162. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68163. if (skeletonAlreadyLoaded === false) {
  68164. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68165. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68166. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68167. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68168. skeletons.push(skeleton);
  68169. loadedSkeletonsIds.push(parsedSkeleton.id);
  68170. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68171. }
  68172. }
  68173. }
  68174. }
  68175. // Morph targets ?
  68176. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68177. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68178. var managerData = _a[_i];
  68179. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68180. }
  68181. }
  68182. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68183. meshes.push(mesh);
  68184. log += "\n\tMesh " + mesh.toString(fullDetails);
  68185. }
  68186. }
  68187. // Connecting parents
  68188. var currentMesh;
  68189. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68190. currentMesh = scene.meshes[index];
  68191. if (currentMesh._waitingParentId) {
  68192. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68193. currentMesh._waitingParentId = null;
  68194. }
  68195. }
  68196. // freeze and compute world matrix application
  68197. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68198. currentMesh = scene.meshes[index];
  68199. if (currentMesh._waitingFreezeWorldMatrix) {
  68200. currentMesh.freezeWorldMatrix();
  68201. currentMesh._waitingFreezeWorldMatrix = null;
  68202. }
  68203. else {
  68204. currentMesh.computeWorldMatrix(true);
  68205. }
  68206. }
  68207. }
  68208. // Particles
  68209. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68210. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68211. var parsedParticleSystem = parsedData.particleSystems[index];
  68212. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68213. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68214. }
  68215. }
  68216. }
  68217. return true;
  68218. }
  68219. catch (err) {
  68220. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68221. if (onError) {
  68222. onError(msg, err);
  68223. }
  68224. else {
  68225. BABYLON.Tools.Log(msg);
  68226. throw err;
  68227. }
  68228. }
  68229. finally {
  68230. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68231. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68232. }
  68233. }
  68234. return false;
  68235. },
  68236. load: function (scene, data, rootUrl, onError) {
  68237. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68238. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68239. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68240. // and avoid problems with multiple concurrent .babylon loads.
  68241. var log = "importScene has failed JSON parse";
  68242. try {
  68243. var parsedData = JSON.parse(data);
  68244. log = "";
  68245. // Scene
  68246. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68247. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68248. }
  68249. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68250. scene.autoClear = parsedData.autoClear;
  68251. }
  68252. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68253. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68254. }
  68255. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68256. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68257. }
  68258. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68259. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68260. }
  68261. // Fog
  68262. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68263. scene.fogMode = parsedData.fogMode;
  68264. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68265. scene.fogStart = parsedData.fogStart;
  68266. scene.fogEnd = parsedData.fogEnd;
  68267. scene.fogDensity = parsedData.fogDensity;
  68268. log += "\tFog mode for scene: ";
  68269. switch (scene.fogMode) {
  68270. // getters not compiling, so using hardcoded
  68271. case 1:
  68272. log += "exp\n";
  68273. break;
  68274. case 2:
  68275. log += "exp2\n";
  68276. break;
  68277. case 3:
  68278. log += "linear\n";
  68279. break;
  68280. }
  68281. }
  68282. //Physics
  68283. if (parsedData.physicsEnabled) {
  68284. var physicsPlugin;
  68285. if (parsedData.physicsEngine === "cannon") {
  68286. physicsPlugin = new BABYLON.CannonJSPlugin();
  68287. }
  68288. else if (parsedData.physicsEngine === "oimo") {
  68289. physicsPlugin = new BABYLON.OimoJSPlugin();
  68290. }
  68291. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68292. //else - default engine, which is currently oimo
  68293. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68294. scene.enablePhysics(physicsGravity, physicsPlugin);
  68295. }
  68296. // Metadata
  68297. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68298. scene.metadata = parsedData.metadata;
  68299. }
  68300. //collisions, if defined. otherwise, default is true
  68301. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68302. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68303. }
  68304. scene.workerCollisions = !!parsedData.workerCollisions;
  68305. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68306. if (!container) {
  68307. return false;
  68308. }
  68309. if (parsedData.autoAnimate) {
  68310. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68311. }
  68312. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68313. scene.setActiveCameraByID(parsedData.activeCameraID);
  68314. }
  68315. // Environment texture
  68316. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68317. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68318. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68319. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68320. if (parsedData.environmentTextureRotationY) {
  68321. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68322. }
  68323. scene.environmentTexture = hdrTexture;
  68324. }
  68325. else {
  68326. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68327. if (parsedData.environmentTextureRotationY) {
  68328. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68329. }
  68330. scene.environmentTexture = cubeTexture;
  68331. }
  68332. if (parsedData.createDefaultSkybox === true) {
  68333. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68334. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68335. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68336. }
  68337. }
  68338. // Finish
  68339. return true;
  68340. }
  68341. catch (err) {
  68342. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68343. if (onError) {
  68344. onError(msg, err);
  68345. }
  68346. else {
  68347. BABYLON.Tools.Log(msg);
  68348. throw err;
  68349. }
  68350. }
  68351. finally {
  68352. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68353. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68354. }
  68355. }
  68356. return false;
  68357. },
  68358. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68359. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68360. return container;
  68361. }
  68362. });
  68363. })(BABYLON || (BABYLON = {}));
  68364. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68365. var BABYLON;
  68366. (function (BABYLON) {
  68367. var FilesInput = /** @class */ (function () {
  68368. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68369. this.onProcessFileCallback = function () { return true; };
  68370. this._engine = engine;
  68371. this._currentScene = scene;
  68372. this._sceneLoadedCallback = sceneLoadedCallback;
  68373. this._progressCallback = progressCallback;
  68374. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68375. this._textureLoadingCallback = textureLoadingCallback;
  68376. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68377. this._onReloadCallback = onReloadCallback;
  68378. this._errorCallback = errorCallback;
  68379. }
  68380. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68381. var _this = this;
  68382. if (elementToMonitor) {
  68383. this._elementToMonitor = elementToMonitor;
  68384. this._dragEnterHandler = function (e) { _this.drag(e); };
  68385. this._dragOverHandler = function (e) { _this.drag(e); };
  68386. this._dropHandler = function (e) { _this.drop(e); };
  68387. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68388. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68389. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68390. }
  68391. };
  68392. FilesInput.prototype.dispose = function () {
  68393. if (!this._elementToMonitor) {
  68394. return;
  68395. }
  68396. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68397. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68398. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68399. };
  68400. FilesInput.prototype.renderFunction = function () {
  68401. if (this._additionalRenderLoopLogicCallback) {
  68402. this._additionalRenderLoopLogicCallback();
  68403. }
  68404. if (this._currentScene) {
  68405. if (this._textureLoadingCallback) {
  68406. var remaining = this._currentScene.getWaitingItemsCount();
  68407. if (remaining > 0) {
  68408. this._textureLoadingCallback(remaining);
  68409. }
  68410. }
  68411. this._currentScene.render();
  68412. }
  68413. };
  68414. FilesInput.prototype.drag = function (e) {
  68415. e.stopPropagation();
  68416. e.preventDefault();
  68417. };
  68418. FilesInput.prototype.drop = function (eventDrop) {
  68419. eventDrop.stopPropagation();
  68420. eventDrop.preventDefault();
  68421. this.loadFiles(eventDrop);
  68422. };
  68423. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68424. var _this = this;
  68425. var reader = folder.createReader();
  68426. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68427. reader.readEntries(function (entries) {
  68428. remaining.count += entries.length;
  68429. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68430. var entry = entries_1[_i];
  68431. if (entry.isFile) {
  68432. entry.file(function (file) {
  68433. file.correctName = relativePath + file.name;
  68434. files.push(file);
  68435. if (--remaining.count === 0) {
  68436. callback();
  68437. }
  68438. });
  68439. }
  68440. else if (entry.isDirectory) {
  68441. _this._traverseFolder(entry, files, remaining, callback);
  68442. }
  68443. }
  68444. if (--remaining.count) {
  68445. callback();
  68446. }
  68447. });
  68448. };
  68449. FilesInput.prototype._processFiles = function (files) {
  68450. for (var i = 0; i < files.length; i++) {
  68451. var name = files[i].correctName.toLowerCase();
  68452. var extension = name.split('.').pop();
  68453. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68454. continue;
  68455. }
  68456. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68457. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68458. this._sceneFileToLoad = files[i];
  68459. }
  68460. else {
  68461. FilesInput.FilesToLoad[name] = files[i];
  68462. }
  68463. }
  68464. };
  68465. FilesInput.prototype.loadFiles = function (event) {
  68466. var _this = this;
  68467. if (this._startingProcessingFilesCallback)
  68468. this._startingProcessingFilesCallback();
  68469. // Handling data transfer via drag'n'drop
  68470. if (event && event.dataTransfer && event.dataTransfer.files) {
  68471. this._filesToLoad = event.dataTransfer.files;
  68472. }
  68473. // Handling files from input files
  68474. if (event && event.target && event.target.files) {
  68475. this._filesToLoad = event.target.files;
  68476. }
  68477. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68478. var files_1 = new Array();
  68479. var folders = [];
  68480. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68481. for (var i = 0; i < this._filesToLoad.length; i++) {
  68482. var fileToLoad = this._filesToLoad[i];
  68483. var name_1 = fileToLoad.name.toLowerCase();
  68484. var entry = void 0;
  68485. fileToLoad.correctName = name_1;
  68486. if (items) {
  68487. var item = items[i];
  68488. if (item.getAsEntry) {
  68489. entry = item.getAsEntry();
  68490. }
  68491. else if (item.webkitGetAsEntry) {
  68492. entry = item.webkitGetAsEntry();
  68493. }
  68494. }
  68495. if (!entry) {
  68496. files_1.push(fileToLoad);
  68497. }
  68498. else {
  68499. if (entry.isDirectory) {
  68500. folders.push(entry);
  68501. }
  68502. else {
  68503. files_1.push(fileToLoad);
  68504. }
  68505. }
  68506. }
  68507. if (folders.length === 0) {
  68508. this._processFiles(files_1);
  68509. this._processReload();
  68510. }
  68511. else {
  68512. var remaining = { count: folders.length };
  68513. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68514. var folder = folders_1[_i];
  68515. this._traverseFolder(folder, files_1, remaining, function () {
  68516. _this._processFiles(files_1);
  68517. if (remaining.count === 0) {
  68518. _this._processReload();
  68519. }
  68520. });
  68521. }
  68522. }
  68523. }
  68524. };
  68525. FilesInput.prototype._processReload = function () {
  68526. if (this._onReloadCallback) {
  68527. this._onReloadCallback(this._sceneFileToLoad);
  68528. }
  68529. else {
  68530. this.reload();
  68531. }
  68532. };
  68533. FilesInput.prototype.reload = function () {
  68534. var _this = this;
  68535. // If a scene file has been provided
  68536. if (this._sceneFileToLoad) {
  68537. if (this._currentScene) {
  68538. if (BABYLON.Tools.errorsCount > 0) {
  68539. BABYLON.Tools.ClearLogCache();
  68540. }
  68541. this._engine.stopRenderLoop();
  68542. }
  68543. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68544. if (_this._progressCallback) {
  68545. _this._progressCallback(progress);
  68546. }
  68547. }).then(function (scene) {
  68548. if (_this._currentScene) {
  68549. _this._currentScene.dispose();
  68550. }
  68551. _this._currentScene = scene;
  68552. if (_this._sceneLoadedCallback) {
  68553. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68554. }
  68555. // Wait for textures and shaders to be ready
  68556. _this._currentScene.executeWhenReady(function () {
  68557. _this._engine.runRenderLoop(function () {
  68558. _this.renderFunction();
  68559. });
  68560. });
  68561. }).catch(function (error) {
  68562. if (_this._errorCallback) {
  68563. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68564. }
  68565. });
  68566. }
  68567. else {
  68568. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68569. }
  68570. };
  68571. FilesInput.FilesToLoad = {};
  68572. return FilesInput;
  68573. }());
  68574. BABYLON.FilesInput = FilesInput;
  68575. })(BABYLON || (BABYLON = {}));
  68576. //# sourceMappingURL=babylon.filesInput.js.map
  68577. var BABYLON;
  68578. (function (BABYLON) {
  68579. /**
  68580. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68581. * The underlying implementation relies on an associative array to ensure the best performances.
  68582. * The value can be anything including 'null' but except 'undefined'
  68583. */
  68584. var StringDictionary = /** @class */ (function () {
  68585. function StringDictionary() {
  68586. this._count = 0;
  68587. this._data = {};
  68588. }
  68589. /**
  68590. * This will clear this dictionary and copy the content from the 'source' one.
  68591. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68592. * @param source the dictionary to take the content from and copy to this dictionary
  68593. */
  68594. StringDictionary.prototype.copyFrom = function (source) {
  68595. var _this = this;
  68596. this.clear();
  68597. source.forEach(function (t, v) { return _this.add(t, v); });
  68598. };
  68599. /**
  68600. * Get a value based from its key
  68601. * @param key the given key to get the matching value from
  68602. * @return the value if found, otherwise undefined is returned
  68603. */
  68604. StringDictionary.prototype.get = function (key) {
  68605. var val = this._data[key];
  68606. if (val !== undefined) {
  68607. return val;
  68608. }
  68609. return undefined;
  68610. };
  68611. /**
  68612. * Get a value from its key or add it if it doesn't exist.
  68613. * This method will ensure you that a given key/data will be present in the dictionary.
  68614. * @param key the given key to get the matching value from
  68615. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68616. * The factory will only be invoked if there's no data for the given key.
  68617. * @return the value corresponding to the key.
  68618. */
  68619. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68620. var val = this.get(key);
  68621. if (val !== undefined) {
  68622. return val;
  68623. }
  68624. val = factory(key);
  68625. if (val) {
  68626. this.add(key, val);
  68627. }
  68628. return val;
  68629. };
  68630. /**
  68631. * Get a value from its key if present in the dictionary otherwise add it
  68632. * @param key the key to get the value from
  68633. * @param val if there's no such key/value pair in the dictionary add it with this value
  68634. * @return the value corresponding to the key
  68635. */
  68636. StringDictionary.prototype.getOrAdd = function (key, val) {
  68637. var curVal = this.get(key);
  68638. if (curVal !== undefined) {
  68639. return curVal;
  68640. }
  68641. this.add(key, val);
  68642. return val;
  68643. };
  68644. /**
  68645. * Check if there's a given key in the dictionary
  68646. * @param key the key to check for
  68647. * @return true if the key is present, false otherwise
  68648. */
  68649. StringDictionary.prototype.contains = function (key) {
  68650. return this._data[key] !== undefined;
  68651. };
  68652. /**
  68653. * Add a new key and its corresponding value
  68654. * @param key the key to add
  68655. * @param value the value corresponding to the key
  68656. * @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
  68657. */
  68658. StringDictionary.prototype.add = function (key, value) {
  68659. if (this._data[key] !== undefined) {
  68660. return false;
  68661. }
  68662. this._data[key] = value;
  68663. ++this._count;
  68664. return true;
  68665. };
  68666. StringDictionary.prototype.set = function (key, value) {
  68667. if (this._data[key] === undefined) {
  68668. return false;
  68669. }
  68670. this._data[key] = value;
  68671. return true;
  68672. };
  68673. /**
  68674. * Get the element of the given key and remove it from the dictionary
  68675. * @param key
  68676. */
  68677. StringDictionary.prototype.getAndRemove = function (key) {
  68678. var val = this.get(key);
  68679. if (val !== undefined) {
  68680. delete this._data[key];
  68681. --this._count;
  68682. return val;
  68683. }
  68684. return null;
  68685. };
  68686. /**
  68687. * Remove a key/value from the dictionary.
  68688. * @param key the key to remove
  68689. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68690. */
  68691. StringDictionary.prototype.remove = function (key) {
  68692. if (this.contains(key)) {
  68693. delete this._data[key];
  68694. --this._count;
  68695. return true;
  68696. }
  68697. return false;
  68698. };
  68699. /**
  68700. * Clear the whole content of the dictionary
  68701. */
  68702. StringDictionary.prototype.clear = function () {
  68703. this._data = {};
  68704. this._count = 0;
  68705. };
  68706. Object.defineProperty(StringDictionary.prototype, "count", {
  68707. get: function () {
  68708. return this._count;
  68709. },
  68710. enumerable: true,
  68711. configurable: true
  68712. });
  68713. /**
  68714. * Execute a callback on each key/val of the dictionary.
  68715. * Note that you can remove any element in this dictionary in the callback implementation
  68716. * @param callback the callback to execute on a given key/value pair
  68717. */
  68718. StringDictionary.prototype.forEach = function (callback) {
  68719. for (var cur in this._data) {
  68720. var val = this._data[cur];
  68721. callback(cur, val);
  68722. }
  68723. };
  68724. /**
  68725. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68726. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68727. * Note that you can remove any element in this dictionary in the callback implementation
  68728. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68729. */
  68730. StringDictionary.prototype.first = function (callback) {
  68731. for (var cur in this._data) {
  68732. var val = this._data[cur];
  68733. var res = callback(cur, val);
  68734. if (res) {
  68735. return res;
  68736. }
  68737. }
  68738. return null;
  68739. };
  68740. return StringDictionary;
  68741. }());
  68742. BABYLON.StringDictionary = StringDictionary;
  68743. })(BABYLON || (BABYLON = {}));
  68744. //# sourceMappingURL=babylon.stringDictionary.js.map
  68745. var BABYLON;
  68746. (function (BABYLON) {
  68747. var Tags = /** @class */ (function () {
  68748. function Tags() {
  68749. }
  68750. Tags.EnableFor = function (obj) {
  68751. obj._tags = obj._tags || {};
  68752. obj.hasTags = function () {
  68753. return Tags.HasTags(obj);
  68754. };
  68755. obj.addTags = function (tagsString) {
  68756. return Tags.AddTagsTo(obj, tagsString);
  68757. };
  68758. obj.removeTags = function (tagsString) {
  68759. return Tags.RemoveTagsFrom(obj, tagsString);
  68760. };
  68761. obj.matchesTagsQuery = function (tagsQuery) {
  68762. return Tags.MatchesQuery(obj, tagsQuery);
  68763. };
  68764. };
  68765. Tags.DisableFor = function (obj) {
  68766. delete obj._tags;
  68767. delete obj.hasTags;
  68768. delete obj.addTags;
  68769. delete obj.removeTags;
  68770. delete obj.matchesTagsQuery;
  68771. };
  68772. Tags.HasTags = function (obj) {
  68773. if (!obj._tags) {
  68774. return false;
  68775. }
  68776. return !BABYLON.Tools.IsEmpty(obj._tags);
  68777. };
  68778. Tags.GetTags = function (obj, asString) {
  68779. if (asString === void 0) { asString = true; }
  68780. if (!obj._tags) {
  68781. return null;
  68782. }
  68783. if (asString) {
  68784. var tagsArray = [];
  68785. for (var tag in obj._tags) {
  68786. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68787. tagsArray.push(tag);
  68788. }
  68789. }
  68790. return tagsArray.join(" ");
  68791. }
  68792. else {
  68793. return obj._tags;
  68794. }
  68795. };
  68796. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68797. // a tag cannot start with '||', '&&', and '!'
  68798. // it cannot contain whitespaces
  68799. Tags.AddTagsTo = function (obj, tagsString) {
  68800. if (!tagsString) {
  68801. return;
  68802. }
  68803. if (typeof tagsString !== "string") {
  68804. return;
  68805. }
  68806. var tags = tagsString.split(" ");
  68807. tags.forEach(function (tag, index, array) {
  68808. Tags._AddTagTo(obj, tag);
  68809. });
  68810. };
  68811. Tags._AddTagTo = function (obj, tag) {
  68812. tag = tag.trim();
  68813. if (tag === "" || tag === "true" || tag === "false") {
  68814. return;
  68815. }
  68816. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68817. return;
  68818. }
  68819. Tags.EnableFor(obj);
  68820. obj._tags[tag] = true;
  68821. };
  68822. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68823. if (!Tags.HasTags(obj)) {
  68824. return;
  68825. }
  68826. var tags = tagsString.split(" ");
  68827. for (var t in tags) {
  68828. Tags._RemoveTagFrom(obj, tags[t]);
  68829. }
  68830. };
  68831. Tags._RemoveTagFrom = function (obj, tag) {
  68832. delete obj._tags[tag];
  68833. };
  68834. Tags.MatchesQuery = function (obj, tagsQuery) {
  68835. if (tagsQuery === undefined) {
  68836. return true;
  68837. }
  68838. if (tagsQuery === "") {
  68839. return Tags.HasTags(obj);
  68840. }
  68841. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68842. };
  68843. return Tags;
  68844. }());
  68845. BABYLON.Tags = Tags;
  68846. })(BABYLON || (BABYLON = {}));
  68847. //# sourceMappingURL=babylon.tags.js.map
  68848. var BABYLON;
  68849. (function (BABYLON) {
  68850. /**
  68851. * Class used to evalaute queries containing `and` and `or` operators
  68852. */
  68853. var AndOrNotEvaluator = /** @class */ (function () {
  68854. function AndOrNotEvaluator() {
  68855. }
  68856. /**
  68857. * Evaluate a query
  68858. * @param query defines the query to evaluate
  68859. * @param evaluateCallback defines the callback used to filter result
  68860. * @returns true if the query matches
  68861. */
  68862. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68863. if (!query.match(/\([^\(\)]*\)/g)) {
  68864. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68865. }
  68866. else {
  68867. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68868. // remove parenthesis
  68869. r = r.slice(1, r.length - 1);
  68870. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68871. });
  68872. }
  68873. if (query === "true") {
  68874. return true;
  68875. }
  68876. if (query === "false") {
  68877. return false;
  68878. }
  68879. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68880. };
  68881. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68882. evaluateCallback = evaluateCallback || (function (r) {
  68883. return r === "true" ? true : false;
  68884. });
  68885. var result;
  68886. var or = parenthesisContent.split("||");
  68887. for (var i in or) {
  68888. if (or.hasOwnProperty(i)) {
  68889. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68890. var and = ori.split("&&");
  68891. if (and.length > 1) {
  68892. for (var j = 0; j < and.length; ++j) {
  68893. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68894. if (andj !== "true" && andj !== "false") {
  68895. if (andj[0] === "!") {
  68896. result = !evaluateCallback(andj.substring(1));
  68897. }
  68898. else {
  68899. result = evaluateCallback(andj);
  68900. }
  68901. }
  68902. else {
  68903. result = andj === "true" ? true : false;
  68904. }
  68905. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68906. ori = "false";
  68907. break;
  68908. }
  68909. }
  68910. }
  68911. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68912. result = true;
  68913. break;
  68914. }
  68915. // result equals false (or undefined)
  68916. if (ori !== "true" && ori !== "false") {
  68917. if (ori[0] === "!") {
  68918. result = !evaluateCallback(ori.substring(1));
  68919. }
  68920. else {
  68921. result = evaluateCallback(ori);
  68922. }
  68923. }
  68924. else {
  68925. result = ori === "true" ? true : false;
  68926. }
  68927. }
  68928. }
  68929. // the whole parenthesis scope is replaced by 'true' or 'false'
  68930. return result ? "true" : "false";
  68931. };
  68932. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68933. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68934. // remove whitespaces
  68935. r = r.replace(/[\s]/g, function () { return ""; });
  68936. return r.length % 2 ? "!" : "";
  68937. });
  68938. booleanString = booleanString.trim();
  68939. if (booleanString === "!true") {
  68940. booleanString = "false";
  68941. }
  68942. else if (booleanString === "!false") {
  68943. booleanString = "true";
  68944. }
  68945. return booleanString;
  68946. };
  68947. return AndOrNotEvaluator;
  68948. }());
  68949. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68950. })(BABYLON || (BABYLON = {}));
  68951. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68952. var BABYLON;
  68953. (function (BABYLON) {
  68954. /**
  68955. * Class used to enable access to IndexedDB
  68956. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68957. */
  68958. var Database = /** @class */ (function () {
  68959. /**
  68960. * Creates a new Database
  68961. * @param urlToScene defines the url to load the scene
  68962. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68963. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68964. */
  68965. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68966. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68967. var _this = this;
  68968. // Handling various flavors of prefixed version of IndexedDB
  68969. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68970. this.callbackManifestChecked = callbackManifestChecked;
  68971. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68972. this.db = null;
  68973. this._enableSceneOffline = false;
  68974. this._enableTexturesOffline = false;
  68975. this.manifestVersionFound = 0;
  68976. this.mustUpdateRessources = false;
  68977. this.hasReachedQuota = false;
  68978. if (!Database.IDBStorageEnabled) {
  68979. this.callbackManifestChecked(true);
  68980. }
  68981. else {
  68982. if (disableManifestCheck) {
  68983. this._enableSceneOffline = true;
  68984. this._enableTexturesOffline = true;
  68985. this.manifestVersionFound = 1;
  68986. BABYLON.Tools.SetImmediate(function () {
  68987. _this.callbackManifestChecked(true);
  68988. });
  68989. }
  68990. else {
  68991. this._checkManifestFile();
  68992. }
  68993. }
  68994. }
  68995. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68996. /**
  68997. * Gets a boolean indicating if scene must be saved in the database
  68998. */
  68999. get: function () {
  69000. return this._enableSceneOffline;
  69001. },
  69002. enumerable: true,
  69003. configurable: true
  69004. });
  69005. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69006. /**
  69007. * Gets a boolean indicating if textures must be saved in the database
  69008. */
  69009. get: function () {
  69010. return this._enableTexturesOffline;
  69011. },
  69012. enumerable: true,
  69013. configurable: true
  69014. });
  69015. Database.prototype._checkManifestFile = function () {
  69016. var _this = this;
  69017. var noManifestFile = function () {
  69018. _this._enableSceneOffline = false;
  69019. _this._enableTexturesOffline = false;
  69020. _this.callbackManifestChecked(false);
  69021. };
  69022. var timeStampUsed = false;
  69023. var manifestURL = this.currentSceneUrl + ".manifest";
  69024. var xhr = new XMLHttpRequest();
  69025. if (navigator.onLine) {
  69026. // Adding a timestamp to by-pass browsers' cache
  69027. timeStampUsed = true;
  69028. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69029. }
  69030. xhr.open("GET", manifestURL, true);
  69031. xhr.addEventListener("load", function () {
  69032. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69033. try {
  69034. var manifestFile = JSON.parse(xhr.response);
  69035. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69036. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69037. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69038. _this.manifestVersionFound = manifestFile.version;
  69039. }
  69040. if (_this.callbackManifestChecked) {
  69041. _this.callbackManifestChecked(true);
  69042. }
  69043. }
  69044. catch (ex) {
  69045. noManifestFile();
  69046. }
  69047. }
  69048. else {
  69049. noManifestFile();
  69050. }
  69051. }, false);
  69052. xhr.addEventListener("error", function (event) {
  69053. if (timeStampUsed) {
  69054. timeStampUsed = false;
  69055. // Let's retry without the timeStamp
  69056. // It could fail when coupled with HTML5 Offline API
  69057. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69058. xhr.open("GET", retryManifestURL, true);
  69059. xhr.send();
  69060. }
  69061. else {
  69062. noManifestFile();
  69063. }
  69064. }, false);
  69065. try {
  69066. xhr.send();
  69067. }
  69068. catch (ex) {
  69069. BABYLON.Tools.Error("Error on XHR send request.");
  69070. this.callbackManifestChecked(false);
  69071. }
  69072. };
  69073. /**
  69074. * Open the database and make it available
  69075. * @param successCallback defines the callback to call on success
  69076. * @param errorCallback defines the callback to call on error
  69077. */
  69078. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69079. var _this = this;
  69080. var handleError = function () {
  69081. _this.isSupported = false;
  69082. if (errorCallback)
  69083. errorCallback();
  69084. };
  69085. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69086. // Your browser doesn't support IndexedDB
  69087. this.isSupported = false;
  69088. if (errorCallback)
  69089. errorCallback();
  69090. }
  69091. else {
  69092. // If the DB hasn't been opened or created yet
  69093. if (!this.db) {
  69094. this.hasReachedQuota = false;
  69095. this.isSupported = true;
  69096. var request = this.idbFactory.open("babylonjs", 1);
  69097. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69098. request.onerror = function (event) {
  69099. handleError();
  69100. };
  69101. // executes when a version change transaction cannot complete due to other active transactions
  69102. request.onblocked = function (event) {
  69103. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69104. handleError();
  69105. };
  69106. // DB has been opened successfully
  69107. request.onsuccess = function (event) {
  69108. _this.db = request.result;
  69109. successCallback();
  69110. };
  69111. // Initialization of the DB. Creating Scenes & Textures stores
  69112. request.onupgradeneeded = function (event) {
  69113. _this.db = (event.target).result;
  69114. if (_this.db) {
  69115. try {
  69116. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69117. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69118. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69119. }
  69120. catch (ex) {
  69121. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69122. handleError();
  69123. }
  69124. }
  69125. };
  69126. }
  69127. // DB has already been created and opened
  69128. else {
  69129. if (successCallback)
  69130. successCallback();
  69131. }
  69132. }
  69133. };
  69134. /**
  69135. * Loads an image from the database
  69136. * @param url defines the url to load from
  69137. * @param image defines the target DOM image
  69138. */
  69139. Database.prototype.loadImageFromDB = function (url, image) {
  69140. var _this = this;
  69141. var completeURL = Database._ReturnFullUrlLocation(url);
  69142. var saveAndLoadImage = function () {
  69143. if (!_this.hasReachedQuota && _this.db !== null) {
  69144. // the texture is not yet in the DB, let's try to save it
  69145. _this._saveImageIntoDBAsync(completeURL, image);
  69146. }
  69147. // If the texture is not in the DB and we've reached the DB quota limit
  69148. // let's load it directly from the web
  69149. else {
  69150. image.src = url;
  69151. }
  69152. };
  69153. if (!this.mustUpdateRessources) {
  69154. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69155. }
  69156. // First time we're download the images or update requested in the manifest file by a version change
  69157. else {
  69158. saveAndLoadImage();
  69159. }
  69160. };
  69161. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69162. if (this.isSupported && this.db !== null) {
  69163. var texture;
  69164. var transaction = this.db.transaction(["textures"]);
  69165. transaction.onabort = function (event) {
  69166. image.src = url;
  69167. };
  69168. transaction.oncomplete = function (event) {
  69169. var blobTextureURL;
  69170. if (texture) {
  69171. var URL = window.URL || window.webkitURL;
  69172. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69173. image.onerror = function () {
  69174. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69175. image.src = url;
  69176. };
  69177. image.src = blobTextureURL;
  69178. }
  69179. else {
  69180. notInDBCallback();
  69181. }
  69182. };
  69183. var getRequest = transaction.objectStore("textures").get(url);
  69184. getRequest.onsuccess = function (event) {
  69185. texture = (event.target).result;
  69186. };
  69187. getRequest.onerror = function (event) {
  69188. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69189. image.src = url;
  69190. };
  69191. }
  69192. else {
  69193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69194. image.src = url;
  69195. }
  69196. };
  69197. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69198. var _this = this;
  69199. if (this.isSupported) {
  69200. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69201. var generateBlobUrl = function () {
  69202. var blobTextureURL;
  69203. if (blob) {
  69204. var URL = window.URL || window.webkitURL;
  69205. try {
  69206. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69207. }
  69208. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69209. catch (ex) {
  69210. blobTextureURL = URL.createObjectURL(blob);
  69211. }
  69212. }
  69213. if (blobTextureURL) {
  69214. image.src = blobTextureURL;
  69215. }
  69216. };
  69217. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69218. var xhr = new XMLHttpRequest(), blob;
  69219. xhr.open("GET", url, true);
  69220. xhr.responseType = "blob";
  69221. xhr.addEventListener("load", function () {
  69222. if (xhr.status === 200 && _this.db) {
  69223. // Blob as response (XHR2)
  69224. blob = xhr.response;
  69225. var transaction = _this.db.transaction(["textures"], "readwrite");
  69226. // the transaction could abort because of a QuotaExceededError error
  69227. transaction.onabort = function (event) {
  69228. try {
  69229. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69230. var srcElement = (event.srcElement || event.target);
  69231. var error = srcElement.error;
  69232. if (error && error.name === "QuotaExceededError") {
  69233. _this.hasReachedQuota = true;
  69234. }
  69235. }
  69236. catch (ex) { }
  69237. generateBlobUrl();
  69238. };
  69239. transaction.oncomplete = function (event) {
  69240. generateBlobUrl();
  69241. };
  69242. var newTexture = { textureUrl: url, data: blob };
  69243. try {
  69244. // Put the blob into the dabase
  69245. var addRequest = transaction.objectStore("textures").put(newTexture);
  69246. addRequest.onsuccess = function (event) {
  69247. };
  69248. addRequest.onerror = function (event) {
  69249. generateBlobUrl();
  69250. };
  69251. }
  69252. catch (ex) {
  69253. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69254. if (ex.code === 25) {
  69255. Database.IsUASupportingBlobStorage = false;
  69256. }
  69257. image.src = url;
  69258. }
  69259. }
  69260. else {
  69261. image.src = url;
  69262. }
  69263. }, false);
  69264. xhr.addEventListener("error", function (event) {
  69265. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69266. image.src = url;
  69267. }, false);
  69268. xhr.send();
  69269. }
  69270. else {
  69271. image.src = url;
  69272. }
  69273. }
  69274. else {
  69275. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69276. image.src = url;
  69277. }
  69278. };
  69279. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69280. var _this = this;
  69281. var updateVersion = function () {
  69282. // the version is not yet in the DB or we need to update it
  69283. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69284. };
  69285. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69286. };
  69287. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69288. var _this = this;
  69289. if (this.isSupported && this.db) {
  69290. var version;
  69291. try {
  69292. var transaction = this.db.transaction(["versions"]);
  69293. transaction.oncomplete = function (event) {
  69294. if (version) {
  69295. // If the version in the JSON file is different from the version in DB
  69296. if (_this.manifestVersionFound !== version.data) {
  69297. _this.mustUpdateRessources = true;
  69298. updateInDBCallback();
  69299. }
  69300. else {
  69301. callback(version.data);
  69302. }
  69303. }
  69304. // version was not found in DB
  69305. else {
  69306. _this.mustUpdateRessources = true;
  69307. updateInDBCallback();
  69308. }
  69309. };
  69310. transaction.onabort = function (event) {
  69311. callback(-1);
  69312. };
  69313. var getRequest = transaction.objectStore("versions").get(url);
  69314. getRequest.onsuccess = function (event) {
  69315. version = (event.target).result;
  69316. };
  69317. getRequest.onerror = function (event) {
  69318. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69319. callback(-1);
  69320. };
  69321. }
  69322. catch (ex) {
  69323. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69324. callback(-1);
  69325. }
  69326. }
  69327. else {
  69328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69329. callback(-1);
  69330. }
  69331. };
  69332. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69333. var _this = this;
  69334. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69335. try {
  69336. // Open a transaction to the database
  69337. var transaction = this.db.transaction(["versions"], "readwrite");
  69338. // the transaction could abort because of a QuotaExceededError error
  69339. transaction.onabort = function (event) {
  69340. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69341. var error = event.srcElement['error'];
  69342. if (error && error.name === "QuotaExceededError") {
  69343. _this.hasReachedQuota = true;
  69344. }
  69345. }
  69346. catch (ex) { }
  69347. callback(-1);
  69348. };
  69349. transaction.oncomplete = function (event) {
  69350. callback(_this.manifestVersionFound);
  69351. };
  69352. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69353. // Put the scene into the database
  69354. var addRequest = transaction.objectStore("versions").put(newVersion);
  69355. addRequest.onsuccess = function (event) {
  69356. };
  69357. addRequest.onerror = function (event) {
  69358. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69359. };
  69360. }
  69361. catch (ex) {
  69362. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69363. callback(-1);
  69364. }
  69365. }
  69366. else {
  69367. callback(-1);
  69368. }
  69369. };
  69370. /**
  69371. * Loads a file from database
  69372. * @param url defines the URL to load from
  69373. * @param sceneLoaded defines a callback to call on success
  69374. * @param progressCallBack defines a callback to call when progress changed
  69375. * @param errorCallback defines a callback to call on error
  69376. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69377. */
  69378. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69379. var _this = this;
  69380. var completeUrl = Database._ReturnFullUrlLocation(url);
  69381. var saveAndLoadFile = function () {
  69382. // the scene is not yet in the DB, let's try to save it
  69383. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69384. };
  69385. this._checkVersionFromDB(completeUrl, function (version) {
  69386. if (version !== -1) {
  69387. if (!_this.mustUpdateRessources) {
  69388. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69389. }
  69390. else {
  69391. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69392. }
  69393. }
  69394. else {
  69395. if (errorCallback) {
  69396. errorCallback();
  69397. }
  69398. }
  69399. });
  69400. };
  69401. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69402. if (this.isSupported && this.db) {
  69403. var targetStore;
  69404. if (url.indexOf(".babylon") !== -1) {
  69405. targetStore = "scenes";
  69406. }
  69407. else {
  69408. targetStore = "textures";
  69409. }
  69410. var file;
  69411. var transaction = this.db.transaction([targetStore]);
  69412. transaction.oncomplete = function (event) {
  69413. if (file) {
  69414. callback(file.data);
  69415. }
  69416. // file was not found in DB
  69417. else {
  69418. notInDBCallback();
  69419. }
  69420. };
  69421. transaction.onabort = function (event) {
  69422. notInDBCallback();
  69423. };
  69424. var getRequest = transaction.objectStore(targetStore).get(url);
  69425. getRequest.onsuccess = function (event) {
  69426. file = (event.target).result;
  69427. };
  69428. getRequest.onerror = function (event) {
  69429. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69430. notInDBCallback();
  69431. };
  69432. }
  69433. else {
  69434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69435. callback();
  69436. }
  69437. };
  69438. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69439. var _this = this;
  69440. if (this.isSupported) {
  69441. var targetStore;
  69442. if (url.indexOf(".babylon") !== -1) {
  69443. targetStore = "scenes";
  69444. }
  69445. else {
  69446. targetStore = "textures";
  69447. }
  69448. // Create XHR
  69449. var xhr = new XMLHttpRequest();
  69450. var fileData;
  69451. xhr.open("GET", url, true);
  69452. if (useArrayBuffer) {
  69453. xhr.responseType = "arraybuffer";
  69454. }
  69455. if (progressCallback) {
  69456. xhr.onprogress = progressCallback;
  69457. }
  69458. xhr.addEventListener("load", function () {
  69459. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69460. // Blob as response (XHR2)
  69461. //fileData = xhr.responseText;
  69462. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69463. if (!_this.hasReachedQuota && _this.db) {
  69464. // Open a transaction to the database
  69465. var transaction = _this.db.transaction([targetStore], "readwrite");
  69466. // the transaction could abort because of a QuotaExceededError error
  69467. transaction.onabort = function (event) {
  69468. try {
  69469. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69470. var error = event.srcElement['error'];
  69471. if (error && error.name === "QuotaExceededError") {
  69472. _this.hasReachedQuota = true;
  69473. }
  69474. }
  69475. catch (ex) { }
  69476. callback(fileData);
  69477. };
  69478. transaction.oncomplete = function (event) {
  69479. callback(fileData);
  69480. };
  69481. var newFile;
  69482. if (targetStore === "scenes") {
  69483. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69484. }
  69485. else {
  69486. newFile = { textureUrl: url, data: fileData };
  69487. }
  69488. try {
  69489. // Put the scene into the database
  69490. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69491. addRequest.onsuccess = function (event) {
  69492. };
  69493. addRequest.onerror = function (event) {
  69494. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69495. };
  69496. }
  69497. catch (ex) {
  69498. callback(fileData);
  69499. }
  69500. }
  69501. else {
  69502. callback(fileData);
  69503. }
  69504. }
  69505. else {
  69506. callback();
  69507. }
  69508. }, false);
  69509. xhr.addEventListener("error", function (event) {
  69510. BABYLON.Tools.Error("error on XHR request.");
  69511. callback();
  69512. }, false);
  69513. xhr.send();
  69514. }
  69515. else {
  69516. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69517. callback();
  69518. }
  69519. };
  69520. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69521. Database.IsUASupportingBlobStorage = true;
  69522. /** Gets a boolean indicating if Database storate is enabled */
  69523. Database.IDBStorageEnabled = true;
  69524. Database._ParseURL = function (url) {
  69525. var a = document.createElement('a');
  69526. a.href = url;
  69527. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69528. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69529. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69530. return absLocation;
  69531. };
  69532. Database._ReturnFullUrlLocation = function (url) {
  69533. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69534. return (Database._ParseURL(window.location.href) + url);
  69535. }
  69536. else {
  69537. return url;
  69538. }
  69539. };
  69540. return Database;
  69541. }());
  69542. BABYLON.Database = Database;
  69543. })(BABYLON || (BABYLON = {}));
  69544. //# sourceMappingURL=babylon.database.js.map
  69545. var BABYLON;
  69546. (function (BABYLON) {
  69547. var FresnelParameters = /** @class */ (function () {
  69548. function FresnelParameters() {
  69549. this._isEnabled = true;
  69550. this.leftColor = BABYLON.Color3.White();
  69551. this.rightColor = BABYLON.Color3.Black();
  69552. this.bias = 0;
  69553. this.power = 1;
  69554. }
  69555. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69556. get: function () {
  69557. return this._isEnabled;
  69558. },
  69559. set: function (value) {
  69560. if (this._isEnabled === value) {
  69561. return;
  69562. }
  69563. this._isEnabled = value;
  69564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69565. },
  69566. enumerable: true,
  69567. configurable: true
  69568. });
  69569. FresnelParameters.prototype.clone = function () {
  69570. var newFresnelParameters = new FresnelParameters();
  69571. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69572. return newFresnelParameters;
  69573. };
  69574. FresnelParameters.prototype.serialize = function () {
  69575. var serializationObject = {};
  69576. serializationObject.isEnabled = this.isEnabled;
  69577. serializationObject.leftColor = this.leftColor.asArray();
  69578. serializationObject.rightColor = this.rightColor.asArray();
  69579. serializationObject.bias = this.bias;
  69580. serializationObject.power = this.power;
  69581. return serializationObject;
  69582. };
  69583. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69584. var fresnelParameters = new FresnelParameters();
  69585. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69586. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69587. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69588. fresnelParameters.bias = parsedFresnelParameters.bias;
  69589. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69590. return fresnelParameters;
  69591. };
  69592. return FresnelParameters;
  69593. }());
  69594. BABYLON.FresnelParameters = FresnelParameters;
  69595. })(BABYLON || (BABYLON = {}));
  69596. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69597. var BABYLON;
  69598. (function (BABYLON) {
  69599. var MultiMaterial = /** @class */ (function (_super) {
  69600. __extends(MultiMaterial, _super);
  69601. function MultiMaterial(name, scene) {
  69602. var _this = _super.call(this, name, scene, true) || this;
  69603. scene.multiMaterials.push(_this);
  69604. _this.subMaterials = new Array();
  69605. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69606. return _this;
  69607. }
  69608. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69609. get: function () {
  69610. return this._subMaterials;
  69611. },
  69612. set: function (value) {
  69613. this._subMaterials = value;
  69614. this._hookArray(value);
  69615. },
  69616. enumerable: true,
  69617. configurable: true
  69618. });
  69619. MultiMaterial.prototype._hookArray = function (array) {
  69620. var _this = this;
  69621. var oldPush = array.push;
  69622. array.push = function () {
  69623. var items = [];
  69624. for (var _i = 0; _i < arguments.length; _i++) {
  69625. items[_i] = arguments[_i];
  69626. }
  69627. var result = oldPush.apply(array, items);
  69628. _this._markAllSubMeshesAsTexturesDirty();
  69629. return result;
  69630. };
  69631. var oldSplice = array.splice;
  69632. array.splice = function (index, deleteCount) {
  69633. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69634. _this._markAllSubMeshesAsTexturesDirty();
  69635. return deleted;
  69636. };
  69637. };
  69638. // Properties
  69639. MultiMaterial.prototype.getSubMaterial = function (index) {
  69640. if (index < 0 || index >= this.subMaterials.length) {
  69641. return this.getScene().defaultMaterial;
  69642. }
  69643. return this.subMaterials[index];
  69644. };
  69645. MultiMaterial.prototype.getActiveTextures = function () {
  69646. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69647. if (subMaterial) {
  69648. return subMaterial.getActiveTextures();
  69649. }
  69650. else {
  69651. return [];
  69652. }
  69653. }));
  69654. var _a;
  69655. };
  69656. // Methods
  69657. MultiMaterial.prototype.getClassName = function () {
  69658. return "MultiMaterial";
  69659. };
  69660. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69661. for (var index = 0; index < this.subMaterials.length; index++) {
  69662. var subMaterial = this.subMaterials[index];
  69663. if (subMaterial) {
  69664. if (subMaterial.storeEffectOnSubMeshes) {
  69665. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69666. return false;
  69667. }
  69668. continue;
  69669. }
  69670. if (!subMaterial.isReady(mesh)) {
  69671. return false;
  69672. }
  69673. }
  69674. }
  69675. return true;
  69676. };
  69677. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69678. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69679. for (var index = 0; index < this.subMaterials.length; index++) {
  69680. var subMaterial = null;
  69681. var current = this.subMaterials[index];
  69682. if (cloneChildren && current) {
  69683. subMaterial = current.clone(name + "-" + current.name);
  69684. }
  69685. else {
  69686. subMaterial = this.subMaterials[index];
  69687. }
  69688. newMultiMaterial.subMaterials.push(subMaterial);
  69689. }
  69690. return newMultiMaterial;
  69691. };
  69692. MultiMaterial.prototype.serialize = function () {
  69693. var serializationObject = {};
  69694. serializationObject.name = this.name;
  69695. serializationObject.id = this.id;
  69696. if (BABYLON.Tags) {
  69697. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69698. }
  69699. serializationObject.materials = [];
  69700. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69701. var subMat = this.subMaterials[matIndex];
  69702. if (subMat) {
  69703. serializationObject.materials.push(subMat.id);
  69704. }
  69705. else {
  69706. serializationObject.materials.push(null);
  69707. }
  69708. }
  69709. return serializationObject;
  69710. };
  69711. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69712. var scene = this.getScene();
  69713. if (!scene) {
  69714. return;
  69715. }
  69716. var index = scene.multiMaterials.indexOf(this);
  69717. if (index >= 0) {
  69718. scene.multiMaterials.splice(index, 1);
  69719. }
  69720. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69721. };
  69722. return MultiMaterial;
  69723. }(BABYLON.Material));
  69724. BABYLON.MultiMaterial = MultiMaterial;
  69725. })(BABYLON || (BABYLON = {}));
  69726. //# sourceMappingURL=babylon.multiMaterial.js.map
  69727. var BABYLON;
  69728. (function (BABYLON) {
  69729. var FreeCameraTouchInput = /** @class */ (function () {
  69730. function FreeCameraTouchInput() {
  69731. this._offsetX = null;
  69732. this._offsetY = null;
  69733. this._pointerPressed = new Array();
  69734. this.touchAngularSensibility = 200000.0;
  69735. this.touchMoveSensibility = 250.0;
  69736. }
  69737. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69738. var _this = this;
  69739. var previousPosition = null;
  69740. if (this._pointerInput === undefined) {
  69741. this._onLostFocus = function (evt) {
  69742. _this._offsetX = null;
  69743. _this._offsetY = null;
  69744. };
  69745. this._pointerInput = function (p, s) {
  69746. var evt = p.event;
  69747. if (evt.pointerType === "mouse") {
  69748. return;
  69749. }
  69750. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69751. if (!noPreventDefault) {
  69752. evt.preventDefault();
  69753. }
  69754. _this._pointerPressed.push(evt.pointerId);
  69755. if (_this._pointerPressed.length !== 1) {
  69756. return;
  69757. }
  69758. previousPosition = {
  69759. x: evt.clientX,
  69760. y: evt.clientY
  69761. };
  69762. }
  69763. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69764. if (!noPreventDefault) {
  69765. evt.preventDefault();
  69766. }
  69767. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69768. if (index === -1) {
  69769. return;
  69770. }
  69771. _this._pointerPressed.splice(index, 1);
  69772. if (index != 0) {
  69773. return;
  69774. }
  69775. previousPosition = null;
  69776. _this._offsetX = null;
  69777. _this._offsetY = null;
  69778. }
  69779. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69780. if (!noPreventDefault) {
  69781. evt.preventDefault();
  69782. }
  69783. if (!previousPosition) {
  69784. return;
  69785. }
  69786. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69787. if (index != 0) {
  69788. return;
  69789. }
  69790. _this._offsetX = evt.clientX - previousPosition.x;
  69791. _this._offsetY = -(evt.clientY - previousPosition.y);
  69792. }
  69793. };
  69794. }
  69795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69796. if (this._onLostFocus) {
  69797. element.addEventListener("blur", this._onLostFocus);
  69798. }
  69799. };
  69800. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69801. if (this._pointerInput && element) {
  69802. if (this._observer) {
  69803. this.camera.getScene().onPointerObservable.remove(this._observer);
  69804. this._observer = null;
  69805. }
  69806. if (this._onLostFocus) {
  69807. element.removeEventListener("blur", this._onLostFocus);
  69808. this._onLostFocus = null;
  69809. }
  69810. this._pointerPressed = [];
  69811. this._offsetX = null;
  69812. this._offsetY = null;
  69813. }
  69814. };
  69815. FreeCameraTouchInput.prototype.checkInputs = function () {
  69816. if (this._offsetX && this._offsetY) {
  69817. var camera = this.camera;
  69818. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69819. if (this._pointerPressed.length > 1) {
  69820. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69821. }
  69822. else {
  69823. var speed = camera._computeLocalCameraSpeed();
  69824. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69825. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69826. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69827. }
  69828. }
  69829. };
  69830. FreeCameraTouchInput.prototype.getClassName = function () {
  69831. return "FreeCameraTouchInput";
  69832. };
  69833. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69834. return "touch";
  69835. };
  69836. __decorate([
  69837. BABYLON.serialize()
  69838. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69839. __decorate([
  69840. BABYLON.serialize()
  69841. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69842. return FreeCameraTouchInput;
  69843. }());
  69844. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69845. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69846. })(BABYLON || (BABYLON = {}));
  69847. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69848. var BABYLON;
  69849. (function (BABYLON) {
  69850. // We're mainly based on the logic defined into the FreeCamera code
  69851. var TouchCamera = /** @class */ (function (_super) {
  69852. __extends(TouchCamera, _super);
  69853. //-- end properties for backward compatibility for inputs
  69854. function TouchCamera(name, position, scene) {
  69855. var _this = _super.call(this, name, position, scene) || this;
  69856. _this.inputs.addTouch();
  69857. _this._setupInputs();
  69858. return _this;
  69859. }
  69860. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69861. //-- Begin properties for backward compatibility for inputs
  69862. get: function () {
  69863. var touch = this.inputs.attached["touch"];
  69864. if (touch)
  69865. return touch.touchAngularSensibility;
  69866. return 0;
  69867. },
  69868. set: function (value) {
  69869. var touch = this.inputs.attached["touch"];
  69870. if (touch)
  69871. touch.touchAngularSensibility = value;
  69872. },
  69873. enumerable: true,
  69874. configurable: true
  69875. });
  69876. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69877. get: function () {
  69878. var touch = this.inputs.attached["touch"];
  69879. if (touch)
  69880. return touch.touchMoveSensibility;
  69881. return 0;
  69882. },
  69883. set: function (value) {
  69884. var touch = this.inputs.attached["touch"];
  69885. if (touch)
  69886. touch.touchMoveSensibility = value;
  69887. },
  69888. enumerable: true,
  69889. configurable: true
  69890. });
  69891. TouchCamera.prototype.getClassName = function () {
  69892. return "TouchCamera";
  69893. };
  69894. TouchCamera.prototype._setupInputs = function () {
  69895. var mouse = this.inputs.attached["mouse"];
  69896. if (mouse) {
  69897. mouse.touchEnabled = false;
  69898. }
  69899. };
  69900. return TouchCamera;
  69901. }(BABYLON.FreeCamera));
  69902. BABYLON.TouchCamera = TouchCamera;
  69903. })(BABYLON || (BABYLON = {}));
  69904. //# sourceMappingURL=babylon.touchCamera.js.map
  69905. var BABYLON;
  69906. (function (BABYLON) {
  69907. var ProceduralTexture = /** @class */ (function (_super) {
  69908. __extends(ProceduralTexture, _super);
  69909. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69910. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69911. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69912. if (isCube === void 0) { isCube = false; }
  69913. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69914. _this.isCube = isCube;
  69915. _this.isEnabled = true;
  69916. _this._currentRefreshId = -1;
  69917. _this._refreshRate = 1;
  69918. _this._vertexBuffers = {};
  69919. _this._uniforms = new Array();
  69920. _this._samplers = new Array();
  69921. _this._textures = {};
  69922. _this._floats = {};
  69923. _this._floatsArrays = {};
  69924. _this._colors3 = {};
  69925. _this._colors4 = {};
  69926. _this._vectors2 = {};
  69927. _this._vectors3 = {};
  69928. _this._matrices = {};
  69929. _this._fallbackTextureUsed = false;
  69930. scene.proceduralTextures.push(_this);
  69931. _this._engine = scene.getEngine();
  69932. _this.name = name;
  69933. _this.isRenderTarget = true;
  69934. _this._size = size;
  69935. _this._generateMipMaps = generateMipMaps;
  69936. _this.setFragment(fragment);
  69937. _this._fallbackTexture = fallbackTexture;
  69938. if (isCube) {
  69939. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69940. _this.setFloat("face", 0);
  69941. }
  69942. else {
  69943. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69944. }
  69945. // VBO
  69946. var vertices = [];
  69947. vertices.push(1, 1);
  69948. vertices.push(-1, 1);
  69949. vertices.push(-1, -1);
  69950. vertices.push(1, -1);
  69951. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69952. _this._createIndexBuffer();
  69953. return _this;
  69954. }
  69955. ProceduralTexture.prototype._createIndexBuffer = function () {
  69956. var engine = this._engine;
  69957. // Indices
  69958. var indices = [];
  69959. indices.push(0);
  69960. indices.push(1);
  69961. indices.push(2);
  69962. indices.push(0);
  69963. indices.push(2);
  69964. indices.push(3);
  69965. this._indexBuffer = engine.createIndexBuffer(indices);
  69966. };
  69967. ProceduralTexture.prototype._rebuild = function () {
  69968. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69969. if (vb) {
  69970. vb._rebuild();
  69971. }
  69972. this._createIndexBuffer();
  69973. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69974. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69975. }
  69976. };
  69977. ProceduralTexture.prototype.reset = function () {
  69978. if (this._effect === undefined) {
  69979. return;
  69980. }
  69981. var engine = this._engine;
  69982. engine._releaseEffect(this._effect);
  69983. };
  69984. ProceduralTexture.prototype.isReady = function () {
  69985. var _this = this;
  69986. var engine = this._engine;
  69987. var shaders;
  69988. if (!this._fragment) {
  69989. return false;
  69990. }
  69991. if (this._fallbackTextureUsed) {
  69992. return true;
  69993. }
  69994. if (this._fragment.fragmentElement !== undefined) {
  69995. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69996. }
  69997. else {
  69998. shaders = { vertex: "procedural", fragment: this._fragment };
  69999. }
  70000. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70001. _this.releaseInternalTexture();
  70002. if (_this._fallbackTexture) {
  70003. _this._texture = _this._fallbackTexture._texture;
  70004. if (_this._texture) {
  70005. _this._texture.incrementReferences();
  70006. }
  70007. }
  70008. _this._fallbackTextureUsed = true;
  70009. });
  70010. return this._effect.isReady();
  70011. };
  70012. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70013. this._currentRefreshId = -1;
  70014. };
  70015. ProceduralTexture.prototype.setFragment = function (fragment) {
  70016. this._fragment = fragment;
  70017. };
  70018. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70019. get: function () {
  70020. return this._refreshRate;
  70021. },
  70022. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70023. set: function (value) {
  70024. this._refreshRate = value;
  70025. this.resetRefreshCounter();
  70026. },
  70027. enumerable: true,
  70028. configurable: true
  70029. });
  70030. ProceduralTexture.prototype._shouldRender = function () {
  70031. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70032. return false;
  70033. }
  70034. if (this._fallbackTextureUsed) {
  70035. return false;
  70036. }
  70037. if (this._currentRefreshId === -1) { // At least render once
  70038. this._currentRefreshId = 1;
  70039. return true;
  70040. }
  70041. if (this.refreshRate === this._currentRefreshId) {
  70042. this._currentRefreshId = 1;
  70043. return true;
  70044. }
  70045. this._currentRefreshId++;
  70046. return false;
  70047. };
  70048. ProceduralTexture.prototype.getRenderSize = function () {
  70049. return this._size;
  70050. };
  70051. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70052. if (this._fallbackTextureUsed) {
  70053. return;
  70054. }
  70055. this.releaseInternalTexture();
  70056. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70057. // Update properties
  70058. this._size = size;
  70059. this._generateMipMaps = generateMipMaps;
  70060. };
  70061. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70062. if (this._uniforms.indexOf(uniformName) === -1) {
  70063. this._uniforms.push(uniformName);
  70064. }
  70065. };
  70066. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70067. if (this._samplers.indexOf(name) === -1) {
  70068. this._samplers.push(name);
  70069. }
  70070. this._textures[name] = texture;
  70071. return this;
  70072. };
  70073. ProceduralTexture.prototype.setFloat = function (name, value) {
  70074. this._checkUniform(name);
  70075. this._floats[name] = value;
  70076. return this;
  70077. };
  70078. ProceduralTexture.prototype.setFloats = function (name, value) {
  70079. this._checkUniform(name);
  70080. this._floatsArrays[name] = value;
  70081. return this;
  70082. };
  70083. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70084. this._checkUniform(name);
  70085. this._colors3[name] = value;
  70086. return this;
  70087. };
  70088. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70089. this._checkUniform(name);
  70090. this._colors4[name] = value;
  70091. return this;
  70092. };
  70093. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70094. this._checkUniform(name);
  70095. this._vectors2[name] = value;
  70096. return this;
  70097. };
  70098. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70099. this._checkUniform(name);
  70100. this._vectors3[name] = value;
  70101. return this;
  70102. };
  70103. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70104. this._checkUniform(name);
  70105. this._matrices[name] = value;
  70106. return this;
  70107. };
  70108. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70109. var scene = this.getScene();
  70110. if (!scene) {
  70111. return;
  70112. }
  70113. var engine = this._engine;
  70114. // Render
  70115. engine.enableEffect(this._effect);
  70116. engine.setState(false);
  70117. // Texture
  70118. for (var name in this._textures) {
  70119. this._effect.setTexture(name, this._textures[name]);
  70120. }
  70121. // Float
  70122. for (name in this._floats) {
  70123. this._effect.setFloat(name, this._floats[name]);
  70124. }
  70125. // Floats
  70126. for (name in this._floatsArrays) {
  70127. this._effect.setArray(name, this._floatsArrays[name]);
  70128. }
  70129. // Color3
  70130. for (name in this._colors3) {
  70131. this._effect.setColor3(name, this._colors3[name]);
  70132. }
  70133. // Color4
  70134. for (name in this._colors4) {
  70135. var color = this._colors4[name];
  70136. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70137. }
  70138. // Vector2
  70139. for (name in this._vectors2) {
  70140. this._effect.setVector2(name, this._vectors2[name]);
  70141. }
  70142. // Vector3
  70143. for (name in this._vectors3) {
  70144. this._effect.setVector3(name, this._vectors3[name]);
  70145. }
  70146. // Matrix
  70147. for (name in this._matrices) {
  70148. this._effect.setMatrix(name, this._matrices[name]);
  70149. }
  70150. if (!this._texture) {
  70151. return;
  70152. }
  70153. if (this.isCube) {
  70154. for (var face = 0; face < 6; face++) {
  70155. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70156. // VBOs
  70157. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70158. this._effect.setFloat("face", face);
  70159. // Clear
  70160. engine.clear(scene.clearColor, true, true, true);
  70161. // Draw order
  70162. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70163. // Mipmaps
  70164. if (face === 5) {
  70165. engine.generateMipMapsForCubemap(this._texture);
  70166. }
  70167. }
  70168. }
  70169. else {
  70170. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70171. // VBOs
  70172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70173. // Clear
  70174. engine.clear(scene.clearColor, true, true, true);
  70175. // Draw order
  70176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70177. }
  70178. // Unbind
  70179. engine.unBindFramebuffer(this._texture, this.isCube);
  70180. if (this.onGenerated) {
  70181. this.onGenerated();
  70182. }
  70183. };
  70184. ProceduralTexture.prototype.clone = function () {
  70185. var textureSize = this.getSize();
  70186. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70187. // Base texture
  70188. newTexture.hasAlpha = this.hasAlpha;
  70189. newTexture.level = this.level;
  70190. // RenderTarget Texture
  70191. newTexture.coordinatesMode = this.coordinatesMode;
  70192. return newTexture;
  70193. };
  70194. ProceduralTexture.prototype.dispose = function () {
  70195. var scene = this.getScene();
  70196. if (!scene) {
  70197. return;
  70198. }
  70199. var index = scene.proceduralTextures.indexOf(this);
  70200. if (index >= 0) {
  70201. scene.proceduralTextures.splice(index, 1);
  70202. }
  70203. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70204. if (vertexBuffer) {
  70205. vertexBuffer.dispose();
  70206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70207. }
  70208. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70209. this._indexBuffer = null;
  70210. }
  70211. _super.prototype.dispose.call(this);
  70212. };
  70213. __decorate([
  70214. BABYLON.serialize()
  70215. ], ProceduralTexture.prototype, "_size", void 0);
  70216. __decorate([
  70217. BABYLON.serialize()
  70218. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70219. __decorate([
  70220. BABYLON.serialize()
  70221. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70222. __decorate([
  70223. BABYLON.serialize()
  70224. ], ProceduralTexture.prototype, "refreshRate", null);
  70225. return ProceduralTexture;
  70226. }(BABYLON.Texture));
  70227. BABYLON.ProceduralTexture = ProceduralTexture;
  70228. })(BABYLON || (BABYLON = {}));
  70229. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70230. var BABYLON;
  70231. (function (BABYLON) {
  70232. var CustomProceduralTexture = /** @class */ (function (_super) {
  70233. __extends(CustomProceduralTexture, _super);
  70234. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70235. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70236. _this._animate = true;
  70237. _this._time = 0;
  70238. _this._texturePath = texturePath;
  70239. //Try to load json
  70240. _this.loadJson(texturePath);
  70241. _this.refreshRate = 1;
  70242. return _this;
  70243. }
  70244. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70245. var _this = this;
  70246. var noConfigFile = function () {
  70247. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70248. try {
  70249. _this.setFragment(_this._texturePath);
  70250. }
  70251. catch (ex) {
  70252. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70253. }
  70254. };
  70255. var configFileUrl = jsonUrl + "/config.json";
  70256. var xhr = new XMLHttpRequest();
  70257. xhr.open("GET", configFileUrl, true);
  70258. xhr.addEventListener("load", function () {
  70259. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70260. try {
  70261. _this._config = JSON.parse(xhr.response);
  70262. _this.updateShaderUniforms();
  70263. _this.updateTextures();
  70264. _this.setFragment(_this._texturePath + "/custom");
  70265. _this._animate = _this._config.animate;
  70266. _this.refreshRate = _this._config.refreshrate;
  70267. }
  70268. catch (ex) {
  70269. noConfigFile();
  70270. }
  70271. }
  70272. else {
  70273. noConfigFile();
  70274. }
  70275. }, false);
  70276. xhr.addEventListener("error", function () {
  70277. noConfigFile();
  70278. }, false);
  70279. try {
  70280. xhr.send();
  70281. }
  70282. catch (ex) {
  70283. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70284. }
  70285. };
  70286. CustomProceduralTexture.prototype.isReady = function () {
  70287. if (!_super.prototype.isReady.call(this)) {
  70288. return false;
  70289. }
  70290. for (var name in this._textures) {
  70291. var texture = this._textures[name];
  70292. if (!texture.isReady()) {
  70293. return false;
  70294. }
  70295. }
  70296. return true;
  70297. };
  70298. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70299. var scene = this.getScene();
  70300. if (this._animate && scene) {
  70301. this._time += scene.getAnimationRatio() * 0.03;
  70302. this.updateShaderUniforms();
  70303. }
  70304. _super.prototype.render.call(this, useCameraPostProcess);
  70305. };
  70306. CustomProceduralTexture.prototype.updateTextures = function () {
  70307. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70308. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70309. }
  70310. };
  70311. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70312. if (this._config) {
  70313. for (var j = 0; j < this._config.uniforms.length; j++) {
  70314. var uniform = this._config.uniforms[j];
  70315. switch (uniform.type) {
  70316. case "float":
  70317. this.setFloat(uniform.name, uniform.value);
  70318. break;
  70319. case "color3":
  70320. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70321. break;
  70322. case "color4":
  70323. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70324. break;
  70325. case "vector2":
  70326. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70327. break;
  70328. case "vector3":
  70329. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70330. break;
  70331. }
  70332. }
  70333. }
  70334. this.setFloat("time", this._time);
  70335. };
  70336. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70337. get: function () {
  70338. return this._animate;
  70339. },
  70340. set: function (value) {
  70341. this._animate = value;
  70342. },
  70343. enumerable: true,
  70344. configurable: true
  70345. });
  70346. return CustomProceduralTexture;
  70347. }(BABYLON.ProceduralTexture));
  70348. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70349. })(BABYLON || (BABYLON = {}));
  70350. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70351. var BABYLON;
  70352. (function (BABYLON) {
  70353. var FreeCameraGamepadInput = /** @class */ (function () {
  70354. function FreeCameraGamepadInput() {
  70355. this.gamepadAngularSensibility = 200;
  70356. this.gamepadMoveSensibility = 40;
  70357. // private members
  70358. this._cameraTransform = BABYLON.Matrix.Identity();
  70359. this._deltaTransform = BABYLON.Vector3.Zero();
  70360. this._vector3 = BABYLON.Vector3.Zero();
  70361. this._vector2 = BABYLON.Vector2.Zero();
  70362. }
  70363. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70364. var _this = this;
  70365. var manager = this.camera.getScene().gamepadManager;
  70366. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70367. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70368. // prioritize XBOX gamepads.
  70369. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70370. _this.gamepad = gamepad;
  70371. }
  70372. }
  70373. });
  70374. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70375. if (_this.gamepad === gamepad) {
  70376. _this.gamepad = null;
  70377. }
  70378. });
  70379. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70380. };
  70381. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70382. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70383. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70384. this.gamepad = null;
  70385. };
  70386. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70387. if (this.gamepad && this.gamepad.leftStick) {
  70388. var camera = this.camera;
  70389. var LSValues = this.gamepad.leftStick;
  70390. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70391. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70392. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70393. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70394. var RSValues = this.gamepad.rightStick;
  70395. if (RSValues) {
  70396. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70397. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70398. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70399. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70400. }
  70401. else {
  70402. RSValues = { x: 0, y: 0 };
  70403. }
  70404. if (!camera.rotationQuaternion) {
  70405. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70406. }
  70407. else {
  70408. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70409. }
  70410. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70411. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70412. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70413. camera.cameraDirection.addInPlace(this._deltaTransform);
  70414. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70415. camera.cameraRotation.addInPlace(this._vector2);
  70416. }
  70417. };
  70418. FreeCameraGamepadInput.prototype.getClassName = function () {
  70419. return "FreeCameraGamepadInput";
  70420. };
  70421. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70422. return "gamepad";
  70423. };
  70424. __decorate([
  70425. BABYLON.serialize()
  70426. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70427. __decorate([
  70428. BABYLON.serialize()
  70429. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70430. return FreeCameraGamepadInput;
  70431. }());
  70432. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70433. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70434. })(BABYLON || (BABYLON = {}));
  70435. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70436. var BABYLON;
  70437. (function (BABYLON) {
  70438. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70439. function ArcRotateCameraGamepadInput() {
  70440. this.gamepadRotationSensibility = 80;
  70441. this.gamepadMoveSensibility = 40;
  70442. }
  70443. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70444. var _this = this;
  70445. var manager = this.camera.getScene().gamepadManager;
  70446. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70447. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70448. // prioritize XBOX gamepads.
  70449. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70450. _this.gamepad = gamepad;
  70451. }
  70452. }
  70453. });
  70454. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70455. if (_this.gamepad === gamepad) {
  70456. _this.gamepad = null;
  70457. }
  70458. });
  70459. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70460. };
  70461. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70462. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70463. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70464. this.gamepad = null;
  70465. };
  70466. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70467. if (this.gamepad) {
  70468. var camera = this.camera;
  70469. var RSValues = this.gamepad.rightStick;
  70470. if (RSValues) {
  70471. if (RSValues.x != 0) {
  70472. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70473. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70474. camera.inertialAlphaOffset += normalizedRX;
  70475. }
  70476. }
  70477. if (RSValues.y != 0) {
  70478. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70479. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70480. camera.inertialBetaOffset += normalizedRY;
  70481. }
  70482. }
  70483. }
  70484. var LSValues = this.gamepad.leftStick;
  70485. if (LSValues && LSValues.y != 0) {
  70486. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70487. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70488. this.camera.inertialRadiusOffset -= normalizedLY;
  70489. }
  70490. }
  70491. }
  70492. };
  70493. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70494. return "ArcRotateCameraGamepadInput";
  70495. };
  70496. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70497. return "gamepad";
  70498. };
  70499. __decorate([
  70500. BABYLON.serialize()
  70501. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70502. __decorate([
  70503. BABYLON.serialize()
  70504. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70505. return ArcRotateCameraGamepadInput;
  70506. }());
  70507. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70508. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70509. })(BABYLON || (BABYLON = {}));
  70510. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70511. var BABYLON;
  70512. (function (BABYLON) {
  70513. var GamepadManager = /** @class */ (function () {
  70514. function GamepadManager(_scene) {
  70515. var _this = this;
  70516. this._scene = _scene;
  70517. this._babylonGamepads = [];
  70518. this._oneGamepadConnected = false;
  70519. this._isMonitoring = false;
  70520. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70521. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70522. this._gamepadEventSupported = false;
  70523. }
  70524. else {
  70525. this._gamepadEventSupported = 'GamepadEvent' in window;
  70526. this._gamepadSupport = (navigator.getGamepads ||
  70527. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70528. }
  70529. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70530. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70531. for (var i in _this._babylonGamepads) {
  70532. var gamepad = _this._babylonGamepads[i];
  70533. if (gamepad && gamepad._isConnected) {
  70534. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70535. }
  70536. }
  70537. });
  70538. this._onGamepadConnectedEvent = function (evt) {
  70539. var gamepad = evt.gamepad;
  70540. if (gamepad.index in _this._babylonGamepads) {
  70541. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70542. return;
  70543. }
  70544. }
  70545. var newGamepad;
  70546. if (_this._babylonGamepads[gamepad.index]) {
  70547. newGamepad = _this._babylonGamepads[gamepad.index];
  70548. newGamepad.browserGamepad = gamepad;
  70549. newGamepad._isConnected = true;
  70550. }
  70551. else {
  70552. newGamepad = _this._addNewGamepad(gamepad);
  70553. }
  70554. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70555. _this._startMonitoringGamepads();
  70556. };
  70557. this._onGamepadDisconnectedEvent = function (evt) {
  70558. var gamepad = evt.gamepad;
  70559. // Remove the gamepad from the list of gamepads to monitor.
  70560. for (var i in _this._babylonGamepads) {
  70561. if (_this._babylonGamepads[i].index === gamepad.index) {
  70562. var disconnectedGamepad = _this._babylonGamepads[i];
  70563. disconnectedGamepad._isConnected = false;
  70564. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70565. break;
  70566. }
  70567. }
  70568. };
  70569. if (this._gamepadSupport) {
  70570. //first add already-connected gamepads
  70571. this._updateGamepadObjects();
  70572. if (this._babylonGamepads.length) {
  70573. this._startMonitoringGamepads();
  70574. }
  70575. // Checking if the gamepad connected event is supported (like in Firefox)
  70576. if (this._gamepadEventSupported) {
  70577. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70578. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70579. }
  70580. else {
  70581. this._startMonitoringGamepads();
  70582. }
  70583. }
  70584. }
  70585. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70586. get: function () {
  70587. return this._babylonGamepads;
  70588. },
  70589. enumerable: true,
  70590. configurable: true
  70591. });
  70592. GamepadManager.prototype.getGamepadByType = function (type) {
  70593. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70594. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70595. var gamepad = _a[_i];
  70596. if (gamepad && gamepad.type === type) {
  70597. return gamepad;
  70598. }
  70599. }
  70600. return null;
  70601. };
  70602. GamepadManager.prototype.dispose = function () {
  70603. if (this._gamepadEventSupported) {
  70604. if (this._onGamepadConnectedEvent) {
  70605. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70606. }
  70607. if (this._onGamepadDisconnectedEvent) {
  70608. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70609. }
  70610. this._onGamepadConnectedEvent = null;
  70611. this._onGamepadDisconnectedEvent = null;
  70612. }
  70613. this._babylonGamepads.forEach(function (gamepad) {
  70614. gamepad.dispose();
  70615. });
  70616. this.onGamepadConnectedObservable.clear();
  70617. this.onGamepadDisconnectedObservable.clear();
  70618. this._oneGamepadConnected = false;
  70619. this._stopMonitoringGamepads();
  70620. this._babylonGamepads = [];
  70621. };
  70622. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70623. if (!this._oneGamepadConnected) {
  70624. this._oneGamepadConnected = true;
  70625. }
  70626. var newGamepad;
  70627. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70628. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70629. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70630. }
  70631. // if pose is supported, use the (WebVR) pose enabled controller
  70632. else if (gamepad.pose) {
  70633. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70634. }
  70635. else {
  70636. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70637. }
  70638. this._babylonGamepads[newGamepad.index] = newGamepad;
  70639. return newGamepad;
  70640. };
  70641. GamepadManager.prototype._startMonitoringGamepads = function () {
  70642. if (!this._isMonitoring) {
  70643. this._isMonitoring = true;
  70644. //back-comp
  70645. if (!this._scene) {
  70646. this._checkGamepadsStatus();
  70647. }
  70648. }
  70649. };
  70650. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70651. this._isMonitoring = false;
  70652. };
  70653. GamepadManager.prototype._checkGamepadsStatus = function () {
  70654. var _this = this;
  70655. // Hack to be compatible Chrome
  70656. this._updateGamepadObjects();
  70657. for (var i in this._babylonGamepads) {
  70658. var gamepad = this._babylonGamepads[i];
  70659. if (!gamepad || !gamepad.isConnected) {
  70660. continue;
  70661. }
  70662. gamepad.update();
  70663. }
  70664. if (this._isMonitoring && !this._scene) {
  70665. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70666. }
  70667. };
  70668. // This function is called only on Chrome, which does not properly support
  70669. // connection/disconnection events and forces you to recopy again the gamepad object
  70670. GamepadManager.prototype._updateGamepadObjects = function () {
  70671. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70672. for (var i = 0; i < gamepads.length; i++) {
  70673. var gamepad = gamepads[i];
  70674. if (gamepad) {
  70675. if (!this._babylonGamepads[gamepad.index]) {
  70676. var newGamepad = this._addNewGamepad(gamepad);
  70677. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70678. }
  70679. else {
  70680. // Forced to copy again this object for Chrome for unknown reason
  70681. this._babylonGamepads[i].browserGamepad = gamepad;
  70682. if (!this._babylonGamepads[i].isConnected) {
  70683. this._babylonGamepads[i]._isConnected = true;
  70684. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70685. }
  70686. }
  70687. }
  70688. }
  70689. };
  70690. return GamepadManager;
  70691. }());
  70692. BABYLON.GamepadManager = GamepadManager;
  70693. })(BABYLON || (BABYLON = {}));
  70694. //# sourceMappingURL=babylon.gamepadManager.js.map
  70695. var BABYLON;
  70696. (function (BABYLON) {
  70697. var StickValues = /** @class */ (function () {
  70698. function StickValues(x, y) {
  70699. this.x = x;
  70700. this.y = y;
  70701. }
  70702. return StickValues;
  70703. }());
  70704. BABYLON.StickValues = StickValues;
  70705. var Gamepad = /** @class */ (function () {
  70706. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70707. if (leftStickX === void 0) { leftStickX = 0; }
  70708. if (leftStickY === void 0) { leftStickY = 1; }
  70709. if (rightStickX === void 0) { rightStickX = 2; }
  70710. if (rightStickY === void 0) { rightStickY = 3; }
  70711. this.id = id;
  70712. this.index = index;
  70713. this.browserGamepad = browserGamepad;
  70714. this._isConnected = true;
  70715. this._invertLeftStickY = false;
  70716. this.type = Gamepad.GAMEPAD;
  70717. this._leftStickAxisX = leftStickX;
  70718. this._leftStickAxisY = leftStickY;
  70719. this._rightStickAxisX = rightStickX;
  70720. this._rightStickAxisY = rightStickY;
  70721. if (this.browserGamepad.axes.length >= 2) {
  70722. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70723. }
  70724. if (this.browserGamepad.axes.length >= 4) {
  70725. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70726. }
  70727. }
  70728. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70729. get: function () {
  70730. return this._isConnected;
  70731. },
  70732. enumerable: true,
  70733. configurable: true
  70734. });
  70735. Gamepad.prototype.onleftstickchanged = function (callback) {
  70736. this._onleftstickchanged = callback;
  70737. };
  70738. Gamepad.prototype.onrightstickchanged = function (callback) {
  70739. this._onrightstickchanged = callback;
  70740. };
  70741. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70742. get: function () {
  70743. return this._leftStick;
  70744. },
  70745. set: function (newValues) {
  70746. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70747. this._onleftstickchanged(newValues);
  70748. }
  70749. this._leftStick = newValues;
  70750. },
  70751. enumerable: true,
  70752. configurable: true
  70753. });
  70754. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70755. get: function () {
  70756. return this._rightStick;
  70757. },
  70758. set: function (newValues) {
  70759. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70760. this._onrightstickchanged(newValues);
  70761. }
  70762. this._rightStick = newValues;
  70763. },
  70764. enumerable: true,
  70765. configurable: true
  70766. });
  70767. Gamepad.prototype.update = function () {
  70768. if (this._leftStick) {
  70769. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70770. if (this._invertLeftStickY) {
  70771. this.leftStick.y *= -1;
  70772. }
  70773. }
  70774. if (this._rightStick) {
  70775. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70776. }
  70777. };
  70778. Gamepad.prototype.dispose = function () {
  70779. };
  70780. Gamepad.GAMEPAD = 0;
  70781. Gamepad.GENERIC = 1;
  70782. Gamepad.XBOX = 2;
  70783. Gamepad.POSE_ENABLED = 3;
  70784. return Gamepad;
  70785. }());
  70786. BABYLON.Gamepad = Gamepad;
  70787. var GenericPad = /** @class */ (function (_super) {
  70788. __extends(GenericPad, _super);
  70789. function GenericPad(id, index, browserGamepad) {
  70790. var _this = _super.call(this, id, index, browserGamepad) || this;
  70791. _this.onButtonDownObservable = new BABYLON.Observable();
  70792. _this.onButtonUpObservable = new BABYLON.Observable();
  70793. _this.type = Gamepad.GENERIC;
  70794. _this._buttons = new Array(browserGamepad.buttons.length);
  70795. return _this;
  70796. }
  70797. GenericPad.prototype.onbuttondown = function (callback) {
  70798. this._onbuttondown = callback;
  70799. };
  70800. GenericPad.prototype.onbuttonup = function (callback) {
  70801. this._onbuttonup = callback;
  70802. };
  70803. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70804. if (newValue !== currentValue) {
  70805. if (newValue === 1) {
  70806. if (this._onbuttondown) {
  70807. this._onbuttondown(buttonIndex);
  70808. }
  70809. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70810. }
  70811. if (newValue === 0) {
  70812. if (this._onbuttonup) {
  70813. this._onbuttonup(buttonIndex);
  70814. }
  70815. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70816. }
  70817. }
  70818. return newValue;
  70819. };
  70820. GenericPad.prototype.update = function () {
  70821. _super.prototype.update.call(this);
  70822. for (var index = 0; index < this._buttons.length; index++) {
  70823. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70824. }
  70825. };
  70826. GenericPad.prototype.dispose = function () {
  70827. _super.prototype.dispose.call(this);
  70828. this.onButtonDownObservable.clear();
  70829. this.onButtonUpObservable.clear();
  70830. };
  70831. return GenericPad;
  70832. }(Gamepad));
  70833. BABYLON.GenericPad = GenericPad;
  70834. })(BABYLON || (BABYLON = {}));
  70835. //# sourceMappingURL=babylon.gamepad.js.map
  70836. var BABYLON;
  70837. (function (BABYLON) {
  70838. /**
  70839. * Defines supported buttons for XBox360 compatible gamepads
  70840. */
  70841. var Xbox360Button;
  70842. (function (Xbox360Button) {
  70843. /** A */
  70844. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70845. /** B */
  70846. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70847. /** X */
  70848. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70849. /** Y */
  70850. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70851. /** Start */
  70852. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70853. /** Back */
  70854. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70855. /** Left button */
  70856. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70857. /** Right button */
  70858. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70859. /** Left stick */
  70860. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70861. /** Right stick */
  70862. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70863. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70864. /** Defines values for XBox360 DPad */
  70865. var Xbox360Dpad;
  70866. (function (Xbox360Dpad) {
  70867. /** Up */
  70868. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70869. /** Down */
  70870. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70871. /** Left */
  70872. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70873. /** Right */
  70874. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70875. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70876. /**
  70877. * Defines a XBox360 gamepad
  70878. */
  70879. var Xbox360Pad = /** @class */ (function (_super) {
  70880. __extends(Xbox360Pad, _super);
  70881. /**
  70882. * Creates a new XBox360 gamepad object
  70883. * @param id defines the id of this gamepad
  70884. * @param index defines its index
  70885. * @param gamepad defines the internal HTML gamepad object
  70886. * @param xboxOne defines if it is a XBox One gamepad
  70887. */
  70888. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70889. if (xboxOne === void 0) { xboxOne = false; }
  70890. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70891. _this._leftTrigger = 0;
  70892. _this._rightTrigger = 0;
  70893. /** Observable raised when a button is pressed */
  70894. _this.onButtonDownObservable = new BABYLON.Observable();
  70895. /** Observable raised when a button is released */
  70896. _this.onButtonUpObservable = new BABYLON.Observable();
  70897. /** Observable raised when a pad is pressed */
  70898. _this.onPadDownObservable = new BABYLON.Observable();
  70899. /** Observable raised when a pad is released */
  70900. _this.onPadUpObservable = new BABYLON.Observable();
  70901. _this._buttonA = 0;
  70902. _this._buttonB = 0;
  70903. _this._buttonX = 0;
  70904. _this._buttonY = 0;
  70905. _this._buttonBack = 0;
  70906. _this._buttonStart = 0;
  70907. _this._buttonLB = 0;
  70908. _this._buttonRB = 0;
  70909. _this._buttonLeftStick = 0;
  70910. _this._buttonRightStick = 0;
  70911. _this._dPadUp = 0;
  70912. _this._dPadDown = 0;
  70913. _this._dPadLeft = 0;
  70914. _this._dPadRight = 0;
  70915. _this._isXboxOnePad = false;
  70916. _this.type = BABYLON.Gamepad.XBOX;
  70917. _this._isXboxOnePad = xboxOne;
  70918. return _this;
  70919. }
  70920. /**
  70921. * Defines the callback to call when left trigger is pressed
  70922. * @param callback defines the callback to use
  70923. */
  70924. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70925. this._onlefttriggerchanged = callback;
  70926. };
  70927. /**
  70928. * Defines the callback to call when right trigger is pressed
  70929. * @param callback defines the callback to use
  70930. */
  70931. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70932. this._onrighttriggerchanged = callback;
  70933. };
  70934. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70935. /**
  70936. * Gets or sets left trigger value
  70937. */
  70938. get: function () {
  70939. return this._leftTrigger;
  70940. },
  70941. set: function (newValue) {
  70942. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70943. this._onlefttriggerchanged(newValue);
  70944. }
  70945. this._leftTrigger = newValue;
  70946. },
  70947. enumerable: true,
  70948. configurable: true
  70949. });
  70950. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70951. /**
  70952. * Gets or sets right trigger value
  70953. */
  70954. get: function () {
  70955. return this._rightTrigger;
  70956. },
  70957. set: function (newValue) {
  70958. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70959. this._onrighttriggerchanged(newValue);
  70960. }
  70961. this._rightTrigger = newValue;
  70962. },
  70963. enumerable: true,
  70964. configurable: true
  70965. });
  70966. /**
  70967. * Defines the callback to call when a button is pressed
  70968. * @param callback defines the callback to use
  70969. */
  70970. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70971. this._onbuttondown = callback;
  70972. };
  70973. /**
  70974. * Defines the callback to call when a button is released
  70975. * @param callback defines the callback to use
  70976. */
  70977. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70978. this._onbuttonup = callback;
  70979. };
  70980. /**
  70981. * Defines the callback to call when a pad is pressed
  70982. * @param callback defines the callback to use
  70983. */
  70984. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70985. this._ondpaddown = callback;
  70986. };
  70987. /**
  70988. * Defines the callback to call when a pad is released
  70989. * @param callback defines the callback to use
  70990. */
  70991. Xbox360Pad.prototype.ondpadup = function (callback) {
  70992. this._ondpadup = callback;
  70993. };
  70994. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70995. if (newValue !== currentValue) {
  70996. if (newValue === 1) {
  70997. if (this._onbuttondown) {
  70998. this._onbuttondown(buttonType);
  70999. }
  71000. this.onButtonDownObservable.notifyObservers(buttonType);
  71001. }
  71002. if (newValue === 0) {
  71003. if (this._onbuttonup) {
  71004. this._onbuttonup(buttonType);
  71005. }
  71006. this.onButtonUpObservable.notifyObservers(buttonType);
  71007. }
  71008. }
  71009. return newValue;
  71010. };
  71011. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71012. if (newValue !== currentValue) {
  71013. if (newValue === 1) {
  71014. if (this._ondpaddown) {
  71015. this._ondpaddown(buttonType);
  71016. }
  71017. this.onPadDownObservable.notifyObservers(buttonType);
  71018. }
  71019. if (newValue === 0) {
  71020. if (this._ondpadup) {
  71021. this._ondpadup(buttonType);
  71022. }
  71023. this.onPadUpObservable.notifyObservers(buttonType);
  71024. }
  71025. }
  71026. return newValue;
  71027. };
  71028. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71029. /** Gets or sets value of A button */
  71030. get: function () {
  71031. return this._buttonA;
  71032. },
  71033. set: function (value) {
  71034. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71040. /** Gets or sets value of B button */
  71041. get: function () {
  71042. return this._buttonB;
  71043. },
  71044. set: function (value) {
  71045. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71051. /** Gets or sets value of X button */
  71052. get: function () {
  71053. return this._buttonX;
  71054. },
  71055. set: function (value) {
  71056. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71057. },
  71058. enumerable: true,
  71059. configurable: true
  71060. });
  71061. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71062. /** Gets or sets value of Y button */
  71063. get: function () {
  71064. return this._buttonY;
  71065. },
  71066. set: function (value) {
  71067. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71068. },
  71069. enumerable: true,
  71070. configurable: true
  71071. });
  71072. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71073. /** Gets or sets value of Start button */
  71074. get: function () {
  71075. return this._buttonStart;
  71076. },
  71077. set: function (value) {
  71078. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71079. },
  71080. enumerable: true,
  71081. configurable: true
  71082. });
  71083. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71084. /** Gets or sets value of Back button */
  71085. get: function () {
  71086. return this._buttonBack;
  71087. },
  71088. set: function (value) {
  71089. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71090. },
  71091. enumerable: true,
  71092. configurable: true
  71093. });
  71094. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71095. /** Gets or sets value of Left button */
  71096. get: function () {
  71097. return this._buttonLB;
  71098. },
  71099. set: function (value) {
  71100. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71101. },
  71102. enumerable: true,
  71103. configurable: true
  71104. });
  71105. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71106. /** Gets or sets value of Right button */
  71107. get: function () {
  71108. return this._buttonRB;
  71109. },
  71110. set: function (value) {
  71111. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71112. },
  71113. enumerable: true,
  71114. configurable: true
  71115. });
  71116. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71117. /** Gets or sets value of left stick */
  71118. get: function () {
  71119. return this._buttonLeftStick;
  71120. },
  71121. set: function (value) {
  71122. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71123. },
  71124. enumerable: true,
  71125. configurable: true
  71126. });
  71127. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71128. /** Gets or sets value of right stick */
  71129. get: function () {
  71130. return this._buttonRightStick;
  71131. },
  71132. set: function (value) {
  71133. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71134. },
  71135. enumerable: true,
  71136. configurable: true
  71137. });
  71138. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71139. /** Gets or sets value of DPad up */
  71140. get: function () {
  71141. return this._dPadUp;
  71142. },
  71143. set: function (value) {
  71144. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71150. /** Gets or sets value of DPad down */
  71151. get: function () {
  71152. return this._dPadDown;
  71153. },
  71154. set: function (value) {
  71155. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71156. },
  71157. enumerable: true,
  71158. configurable: true
  71159. });
  71160. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71161. /** Gets or sets value of DPad left */
  71162. get: function () {
  71163. return this._dPadLeft;
  71164. },
  71165. set: function (value) {
  71166. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71167. },
  71168. enumerable: true,
  71169. configurable: true
  71170. });
  71171. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71172. /** Gets or sets value of DPad right */
  71173. get: function () {
  71174. return this._dPadRight;
  71175. },
  71176. set: function (value) {
  71177. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71178. },
  71179. enumerable: true,
  71180. configurable: true
  71181. });
  71182. /**
  71183. * Force the gamepad to synchronize with device values
  71184. */
  71185. Xbox360Pad.prototype.update = function () {
  71186. _super.prototype.update.call(this);
  71187. if (this._isXboxOnePad) {
  71188. this.buttonA = this.browserGamepad.buttons[0].value;
  71189. this.buttonB = this.browserGamepad.buttons[1].value;
  71190. this.buttonX = this.browserGamepad.buttons[2].value;
  71191. this.buttonY = this.browserGamepad.buttons[3].value;
  71192. this.buttonLB = this.browserGamepad.buttons[4].value;
  71193. this.buttonRB = this.browserGamepad.buttons[5].value;
  71194. this.leftTrigger = this.browserGamepad.axes[2];
  71195. this.rightTrigger = this.browserGamepad.axes[5];
  71196. this.buttonBack = this.browserGamepad.buttons[9].value;
  71197. this.buttonStart = this.browserGamepad.buttons[8].value;
  71198. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71199. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71200. this.dPadUp = this.browserGamepad.buttons[11].value;
  71201. this.dPadDown = this.browserGamepad.buttons[12].value;
  71202. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71203. this.dPadRight = this.browserGamepad.buttons[14].value;
  71204. }
  71205. else {
  71206. this.buttonA = this.browserGamepad.buttons[0].value;
  71207. this.buttonB = this.browserGamepad.buttons[1].value;
  71208. this.buttonX = this.browserGamepad.buttons[2].value;
  71209. this.buttonY = this.browserGamepad.buttons[3].value;
  71210. this.buttonLB = this.browserGamepad.buttons[4].value;
  71211. this.buttonRB = this.browserGamepad.buttons[5].value;
  71212. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71213. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71214. this.buttonBack = this.browserGamepad.buttons[8].value;
  71215. this.buttonStart = this.browserGamepad.buttons[9].value;
  71216. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71217. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71218. this.dPadUp = this.browserGamepad.buttons[12].value;
  71219. this.dPadDown = this.browserGamepad.buttons[13].value;
  71220. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71221. this.dPadRight = this.browserGamepad.buttons[15].value;
  71222. }
  71223. };
  71224. Xbox360Pad.prototype.dispose = function () {
  71225. _super.prototype.dispose.call(this);
  71226. this.onButtonDownObservable.clear();
  71227. this.onButtonUpObservable.clear();
  71228. this.onPadDownObservable.clear();
  71229. this.onPadUpObservable.clear();
  71230. };
  71231. return Xbox360Pad;
  71232. }(BABYLON.Gamepad));
  71233. BABYLON.Xbox360Pad = Xbox360Pad;
  71234. })(BABYLON || (BABYLON = {}));
  71235. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71236. var BABYLON;
  71237. (function (BABYLON) {
  71238. /**
  71239. * Defines the types of pose enabled controllers that are supported
  71240. */
  71241. var PoseEnabledControllerType;
  71242. (function (PoseEnabledControllerType) {
  71243. /**
  71244. * HTC Vive
  71245. */
  71246. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71247. /**
  71248. * Oculus Rift
  71249. */
  71250. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71251. /**
  71252. * Windows mixed reality
  71253. */
  71254. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71255. /**
  71256. * Samsung gear VR
  71257. */
  71258. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71259. /**
  71260. * Google Daydream
  71261. */
  71262. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71263. /**
  71264. * Generic
  71265. */
  71266. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71267. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71268. /**
  71269. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71270. */
  71271. var PoseEnabledControllerHelper = /** @class */ (function () {
  71272. function PoseEnabledControllerHelper() {
  71273. }
  71274. /**
  71275. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71276. * @param vrGamepad the gamepad to initialized
  71277. * @returns a vr controller of the type the gamepad identified as
  71278. */
  71279. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71280. // Oculus Touch
  71281. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71282. return new BABYLON.OculusTouchController(vrGamepad);
  71283. }
  71284. // Windows Mixed Reality controllers
  71285. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71286. return new BABYLON.WindowsMotionController(vrGamepad);
  71287. }
  71288. // HTC Vive
  71289. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71290. return new BABYLON.ViveController(vrGamepad);
  71291. }
  71292. // Samsung/Oculus Gear VR or Oculus Go
  71293. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71294. return new BABYLON.GearVRController(vrGamepad);
  71295. }
  71296. // Google Daydream
  71297. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71298. return new BABYLON.DaydreamController(vrGamepad);
  71299. }
  71300. // Generic
  71301. else {
  71302. return new BABYLON.GenericController(vrGamepad);
  71303. }
  71304. };
  71305. return PoseEnabledControllerHelper;
  71306. }());
  71307. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71308. /**
  71309. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71310. */
  71311. var PoseEnabledController = /** @class */ (function (_super) {
  71312. __extends(PoseEnabledController, _super);
  71313. /**
  71314. * Creates a new PoseEnabledController from a gamepad
  71315. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71316. */
  71317. function PoseEnabledController(browserGamepad) {
  71318. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71319. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71320. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71321. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71322. /**
  71323. * The device position in babylon space
  71324. */
  71325. _this.devicePosition = BABYLON.Vector3.Zero();
  71326. /**
  71327. * The device rotation in babylon space
  71328. */
  71329. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71330. /**
  71331. * The scale factor of the device in babylon space
  71332. */
  71333. _this.deviceScaleFactor = 1;
  71334. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71335. /**
  71336. * Internal, matrix used to convert room space to babylon space
  71337. */
  71338. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71339. /**
  71340. * Node to be used when casting a ray from the controller
  71341. */
  71342. _this._pointingPoseNode = null;
  71343. _this._workingMatrix = BABYLON.Matrix.Identity();
  71344. /**
  71345. * @hidden
  71346. */
  71347. _this._meshAttachedObservable = new BABYLON.Observable();
  71348. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71349. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71350. _this.position = BABYLON.Vector3.Zero();
  71351. _this.rotationQuaternion = new BABYLON.Quaternion();
  71352. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71353. _this._calculatedRotation = new BABYLON.Quaternion();
  71354. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71355. return _this;
  71356. }
  71357. /**
  71358. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71359. */
  71360. PoseEnabledController.prototype.update = function () {
  71361. _super.prototype.update.call(this);
  71362. var pose = this.browserGamepad.pose;
  71363. this.updateFromDevice(pose);
  71364. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71365. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71366. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71367. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71368. if (this._mesh) {
  71369. this._mesh.position.copyFrom(this.devicePosition);
  71370. if (this._mesh.rotationQuaternion) {
  71371. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71372. }
  71373. }
  71374. };
  71375. /**
  71376. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71377. * @param poseData raw pose fromthe device
  71378. */
  71379. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71380. if (poseData) {
  71381. this.rawPose = poseData;
  71382. if (poseData.position) {
  71383. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71384. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71385. this._deviceRoomPosition.z *= -1;
  71386. }
  71387. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71388. this._calculatedPosition.addInPlace(this.position);
  71389. }
  71390. var pose = this.rawPose;
  71391. if (poseData.orientation && pose.orientation) {
  71392. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71393. if (this._mesh) {
  71394. if (this._mesh.getScene().useRightHandedSystem) {
  71395. this._deviceRoomRotationQuaternion.z *= -1;
  71396. this._deviceRoomRotationQuaternion.w *= -1;
  71397. }
  71398. else {
  71399. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71400. }
  71401. }
  71402. // if the camera is set, rotate to the camera's rotation
  71403. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71404. }
  71405. }
  71406. };
  71407. /**
  71408. * Attaches a mesh to the controller
  71409. * @param mesh the mesh to be attached
  71410. */
  71411. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71412. if (this._mesh) {
  71413. this._mesh.parent = null;
  71414. }
  71415. this._mesh = mesh;
  71416. if (this._poseControlledCamera) {
  71417. this._mesh.parent = this._poseControlledCamera;
  71418. }
  71419. if (!this._mesh.rotationQuaternion) {
  71420. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71421. }
  71422. // Sync controller mesh and pointing pose node's state with controller
  71423. this.update();
  71424. if (this._pointingPoseNode) {
  71425. var parents = [];
  71426. var obj = this._pointingPoseNode;
  71427. while (obj.parent) {
  71428. parents.push(obj.parent);
  71429. obj = obj.parent;
  71430. }
  71431. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71432. }
  71433. this._meshAttachedObservable.notifyObservers(mesh);
  71434. };
  71435. /**
  71436. * Attaches the controllers mesh to a camera
  71437. * @param camera the camera the mesh should be attached to
  71438. */
  71439. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71440. this._poseControlledCamera = camera;
  71441. if (this._mesh) {
  71442. this._mesh.parent = this._poseControlledCamera;
  71443. }
  71444. };
  71445. /**
  71446. * Disposes of the controller
  71447. */
  71448. PoseEnabledController.prototype.dispose = function () {
  71449. if (this._mesh) {
  71450. this._mesh.dispose();
  71451. }
  71452. this._mesh = null;
  71453. _super.prototype.dispose.call(this);
  71454. };
  71455. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71456. /**
  71457. * The mesh that is attached to the controller
  71458. */
  71459. get: function () {
  71460. return this._mesh;
  71461. },
  71462. enumerable: true,
  71463. configurable: true
  71464. });
  71465. /**
  71466. * Gets the ray of the controller in the direction the controller is pointing
  71467. * @param length the length the resulting ray should be
  71468. * @returns a ray in the direction the controller is pointing
  71469. */
  71470. PoseEnabledController.prototype.getForwardRay = function (length) {
  71471. if (length === void 0) { length = 100; }
  71472. if (!this.mesh) {
  71473. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71474. }
  71475. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71476. var origin = m.getTranslation();
  71477. var forward = new BABYLON.Vector3(0, 0, -1);
  71478. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71479. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71480. return new BABYLON.Ray(origin, direction, length);
  71481. };
  71482. /**
  71483. * Name of the child mesh that can be used to cast a ray from the controller
  71484. */
  71485. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71486. return PoseEnabledController;
  71487. }(BABYLON.Gamepad));
  71488. BABYLON.PoseEnabledController = PoseEnabledController;
  71489. })(BABYLON || (BABYLON = {}));
  71490. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71491. var BABYLON;
  71492. (function (BABYLON) {
  71493. /**
  71494. * Defines the WebVRController object that represents controllers tracked in 3D space
  71495. */
  71496. var WebVRController = /** @class */ (function (_super) {
  71497. __extends(WebVRController, _super);
  71498. /**
  71499. * Creates a new WebVRController from a gamepad
  71500. * @param vrGamepad the gamepad that the WebVRController should be created from
  71501. */
  71502. function WebVRController(vrGamepad) {
  71503. var _this = _super.call(this, vrGamepad) || this;
  71504. // Observables
  71505. /**
  71506. * Fired when the trigger state has changed
  71507. */
  71508. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71509. /**
  71510. * Fired when the main button state has changed
  71511. */
  71512. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71513. /**
  71514. * Fired when the secondary button state has changed
  71515. */
  71516. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71517. /**
  71518. * Fired when the pad state has changed
  71519. */
  71520. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71521. /**
  71522. * Fired when controllers stick values have changed
  71523. */
  71524. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71525. /**
  71526. * X and Y axis corrisponding to the controllers joystick
  71527. */
  71528. _this.pad = { x: 0, y: 0 };
  71529. // avoid GC, store state in a tmp object
  71530. _this._changes = {
  71531. pressChanged: false,
  71532. touchChanged: false,
  71533. valueChanged: false,
  71534. changed: false
  71535. };
  71536. _this._buttons = new Array(vrGamepad.buttons.length);
  71537. _this.hand = vrGamepad.hand;
  71538. return _this;
  71539. }
  71540. /**
  71541. * Fired when a controller button's state has changed
  71542. * @param callback the callback containing the button that was modified
  71543. */
  71544. WebVRController.prototype.onButtonStateChange = function (callback) {
  71545. this._onButtonStateChange = callback;
  71546. };
  71547. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71548. /**
  71549. * The default controller model for the controller
  71550. */
  71551. get: function () {
  71552. return this._defaultModel;
  71553. },
  71554. enumerable: true,
  71555. configurable: true
  71556. });
  71557. /**
  71558. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71559. */
  71560. WebVRController.prototype.update = function () {
  71561. _super.prototype.update.call(this);
  71562. for (var index = 0; index < this._buttons.length; index++) {
  71563. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71564. }
  71565. ;
  71566. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71567. this.pad.x = this.leftStick.x;
  71568. this.pad.y = this.leftStick.y;
  71569. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71570. }
  71571. };
  71572. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71573. if (!newState) {
  71574. newState = {
  71575. pressed: false,
  71576. touched: false,
  71577. value: 0
  71578. };
  71579. }
  71580. if (!currentState) {
  71581. this._buttons[buttonIndex] = {
  71582. pressed: newState.pressed,
  71583. touched: newState.touched,
  71584. value: newState.value
  71585. };
  71586. return;
  71587. }
  71588. this._checkChanges(newState, currentState);
  71589. if (this._changes.changed) {
  71590. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71591. this._handleButtonChange(buttonIndex, newState, this._changes);
  71592. }
  71593. this._buttons[buttonIndex].pressed = newState.pressed;
  71594. this._buttons[buttonIndex].touched = newState.touched;
  71595. // oculus triggers are never 0, thou not touched.
  71596. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71597. };
  71598. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71599. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71600. this._changes.touchChanged = newState.touched !== currentState.touched;
  71601. this._changes.valueChanged = newState.value !== currentState.value;
  71602. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71603. return this._changes;
  71604. };
  71605. /**
  71606. * Disposes of th webVRCOntroller
  71607. */
  71608. WebVRController.prototype.dispose = function () {
  71609. _super.prototype.dispose.call(this);
  71610. this.onTriggerStateChangedObservable.clear();
  71611. this.onMainButtonStateChangedObservable.clear();
  71612. this.onSecondaryButtonStateChangedObservable.clear();
  71613. this.onPadStateChangedObservable.clear();
  71614. this.onPadValuesChangedObservable.clear();
  71615. };
  71616. return WebVRController;
  71617. }(BABYLON.PoseEnabledController));
  71618. BABYLON.WebVRController = WebVRController;
  71619. })(BABYLON || (BABYLON = {}));
  71620. //# sourceMappingURL=babylon.webVRController.js.map
  71621. var BABYLON;
  71622. (function (BABYLON) {
  71623. /**
  71624. * Oculus Touch Controller
  71625. */
  71626. var OculusTouchController = /** @class */ (function (_super) {
  71627. __extends(OculusTouchController, _super);
  71628. /**
  71629. * Creates a new OculusTouchController from a gamepad
  71630. * @param vrGamepad the gamepad that the controller should be created from
  71631. */
  71632. function OculusTouchController(vrGamepad) {
  71633. var _this = _super.call(this, vrGamepad) || this;
  71634. /**
  71635. * Fired when the secondary trigger on this controller is modified
  71636. */
  71637. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71638. /**
  71639. * Fired when the thumb rest on this controller is modified
  71640. */
  71641. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71642. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71643. return _this;
  71644. }
  71645. /**
  71646. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71647. * @param scene scene in which to add meshes
  71648. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71649. */
  71650. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71651. var _this = this;
  71652. var meshName;
  71653. // Hand
  71654. if (this.hand === 'left') {
  71655. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71656. }
  71657. else { // Right is the default if no hand is specified
  71658. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71659. }
  71660. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71661. /*
  71662. Parent Mesh name: oculus_touch_left
  71663. - body
  71664. - trigger
  71665. - thumbstick
  71666. - grip
  71667. - button_y
  71668. - button_x
  71669. - button_enter
  71670. */
  71671. _this._defaultModel = newMeshes[1];
  71672. _this.attachToMesh(_this._defaultModel);
  71673. if (meshLoaded) {
  71674. meshLoaded(_this._defaultModel);
  71675. }
  71676. });
  71677. };
  71678. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71679. /**
  71680. * Fired when the A button on this controller is modified
  71681. */
  71682. get: function () {
  71683. if (this.hand === 'right') {
  71684. return this.onMainButtonStateChangedObservable;
  71685. }
  71686. else {
  71687. throw new Error('No A button on left hand');
  71688. }
  71689. },
  71690. enumerable: true,
  71691. configurable: true
  71692. });
  71693. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71694. /**
  71695. * Fired when the B button on this controller is modified
  71696. */
  71697. get: function () {
  71698. if (this.hand === 'right') {
  71699. return this.onSecondaryButtonStateChangedObservable;
  71700. }
  71701. else {
  71702. throw new Error('No B button on left hand');
  71703. }
  71704. },
  71705. enumerable: true,
  71706. configurable: true
  71707. });
  71708. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71709. /**
  71710. * Fired when the X button on this controller is modified
  71711. */
  71712. get: function () {
  71713. if (this.hand === 'left') {
  71714. return this.onMainButtonStateChangedObservable;
  71715. }
  71716. else {
  71717. throw new Error('No X button on right hand');
  71718. }
  71719. },
  71720. enumerable: true,
  71721. configurable: true
  71722. });
  71723. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71724. /**
  71725. * Fired when the Y button on this controller is modified
  71726. */
  71727. get: function () {
  71728. if (this.hand === 'left') {
  71729. return this.onSecondaryButtonStateChangedObservable;
  71730. }
  71731. else {
  71732. throw new Error('No Y button on right hand');
  71733. }
  71734. },
  71735. enumerable: true,
  71736. configurable: true
  71737. });
  71738. /**
  71739. * Called once for each button that changed state since the last frame
  71740. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71741. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71742. * 2) secondary trigger (same)
  71743. * 3) A (right) X (left), touch, pressed = value
  71744. * 4) B / Y
  71745. * 5) thumb rest
  71746. * @param buttonIdx Which button index changed
  71747. * @param state New state of the button
  71748. * @param changes Which properties on the state changed since last frame
  71749. */
  71750. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71751. var notifyObject = state; //{ state: state, changes: changes };
  71752. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71753. switch (buttonIdx) {
  71754. case 0:
  71755. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71756. return;
  71757. case 1: // index trigger
  71758. if (this._defaultModel) {
  71759. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71760. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71761. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71762. }
  71763. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71764. return;
  71765. case 2: // secondary trigger
  71766. if (this._defaultModel) {
  71767. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71768. }
  71769. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71770. return;
  71771. case 3:
  71772. if (this._defaultModel) {
  71773. if (notifyObject.pressed) {
  71774. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71775. }
  71776. else {
  71777. (this._defaultModel.getChildren()[1]).position.y = 0;
  71778. }
  71779. }
  71780. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71781. return;
  71782. case 4:
  71783. if (this._defaultModel) {
  71784. if (notifyObject.pressed) {
  71785. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71786. }
  71787. else {
  71788. (this._defaultModel.getChildren()[2]).position.y = 0;
  71789. }
  71790. }
  71791. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71792. return;
  71793. case 5:
  71794. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71795. return;
  71796. }
  71797. };
  71798. /**
  71799. * Base Url for the controller model.
  71800. */
  71801. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71802. /**
  71803. * File name for the left controller model.
  71804. */
  71805. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71806. /**
  71807. * File name for the right controller model.
  71808. */
  71809. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71810. return OculusTouchController;
  71811. }(BABYLON.WebVRController));
  71812. BABYLON.OculusTouchController = OculusTouchController;
  71813. })(BABYLON || (BABYLON = {}));
  71814. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71815. var BABYLON;
  71816. (function (BABYLON) {
  71817. /**
  71818. * Vive Controller
  71819. */
  71820. var ViveController = /** @class */ (function (_super) {
  71821. __extends(ViveController, _super);
  71822. /**
  71823. * Creates a new ViveController from a gamepad
  71824. * @param vrGamepad the gamepad that the controller should be created from
  71825. */
  71826. function ViveController(vrGamepad) {
  71827. var _this = _super.call(this, vrGamepad) || this;
  71828. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71829. _this._invertLeftStickY = true;
  71830. return _this;
  71831. }
  71832. /**
  71833. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71834. * @param scene scene in which to add meshes
  71835. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71836. */
  71837. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71838. var _this = this;
  71839. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71840. /*
  71841. Parent Mesh name: ViveWand
  71842. - body
  71843. - r_gripper
  71844. - l_gripper
  71845. - menu_button
  71846. - system_button
  71847. - trackpad
  71848. - trigger
  71849. - LED
  71850. */
  71851. _this._defaultModel = newMeshes[1];
  71852. _this.attachToMesh(_this._defaultModel);
  71853. if (meshLoaded) {
  71854. meshLoaded(_this._defaultModel);
  71855. }
  71856. });
  71857. };
  71858. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71859. /**
  71860. * Fired when the left button on this controller is modified
  71861. */
  71862. get: function () {
  71863. return this.onMainButtonStateChangedObservable;
  71864. },
  71865. enumerable: true,
  71866. configurable: true
  71867. });
  71868. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71869. /**
  71870. * Fired when the right button on this controller is modified
  71871. */
  71872. get: function () {
  71873. return this.onMainButtonStateChangedObservable;
  71874. },
  71875. enumerable: true,
  71876. configurable: true
  71877. });
  71878. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71879. /**
  71880. * Fired when the menu button on this controller is modified
  71881. */
  71882. get: function () {
  71883. return this.onSecondaryButtonStateChangedObservable;
  71884. },
  71885. enumerable: true,
  71886. configurable: true
  71887. });
  71888. /**
  71889. * Called once for each button that changed state since the last frame
  71890. * Vive mapping:
  71891. * 0: touchpad
  71892. * 1: trigger
  71893. * 2: left AND right buttons
  71894. * 3: menu button
  71895. * @param buttonIdx Which button index changed
  71896. * @param state New state of the button
  71897. * @param changes Which properties on the state changed since last frame
  71898. */
  71899. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71900. var notifyObject = state; //{ state: state, changes: changes };
  71901. switch (buttonIdx) {
  71902. case 0:
  71903. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71904. return;
  71905. case 1: // index trigger
  71906. if (this._defaultModel) {
  71907. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71908. }
  71909. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71910. return;
  71911. case 2: // left AND right button
  71912. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71913. return;
  71914. case 3:
  71915. if (this._defaultModel) {
  71916. if (notifyObject.pressed) {
  71917. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71918. }
  71919. else {
  71920. (this._defaultModel.getChildren()[2]).position.y = 0;
  71921. }
  71922. }
  71923. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71924. return;
  71925. }
  71926. };
  71927. /**
  71928. * Base Url for the controller model.
  71929. */
  71930. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71931. /**
  71932. * File name for the controller model.
  71933. */
  71934. ViveController.MODEL_FILENAME = 'wand.babylon';
  71935. return ViveController;
  71936. }(BABYLON.WebVRController));
  71937. BABYLON.ViveController = ViveController;
  71938. })(BABYLON || (BABYLON = {}));
  71939. //# sourceMappingURL=babylon.viveController.js.map
  71940. var BABYLON;
  71941. (function (BABYLON) {
  71942. /**
  71943. * Generic Controller
  71944. */
  71945. var GenericController = /** @class */ (function (_super) {
  71946. __extends(GenericController, _super);
  71947. /**
  71948. * Creates a new GenericController from a gamepad
  71949. * @param vrGamepad the gamepad that the controller should be created from
  71950. */
  71951. function GenericController(vrGamepad) {
  71952. return _super.call(this, vrGamepad) || this;
  71953. }
  71954. /**
  71955. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71956. * @param scene scene in which to add meshes
  71957. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71958. */
  71959. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71960. var _this = this;
  71961. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71962. _this._defaultModel = newMeshes[1];
  71963. _this.attachToMesh(_this._defaultModel);
  71964. if (meshLoaded) {
  71965. meshLoaded(_this._defaultModel);
  71966. }
  71967. });
  71968. };
  71969. /**
  71970. * Called once for each button that changed state since the last frame
  71971. * @param buttonIdx Which button index changed
  71972. * @param state New state of the button
  71973. * @param changes Which properties on the state changed since last frame
  71974. */
  71975. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71976. console.log("Button id: " + buttonIdx + "state: ");
  71977. console.dir(state);
  71978. };
  71979. /**
  71980. * Base Url for the controller model.
  71981. */
  71982. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71983. /**
  71984. * File name for the controller model.
  71985. */
  71986. GenericController.MODEL_FILENAME = 'generic.babylon';
  71987. return GenericController;
  71988. }(BABYLON.WebVRController));
  71989. BABYLON.GenericController = GenericController;
  71990. })(BABYLON || (BABYLON = {}));
  71991. //# sourceMappingURL=babylon.genericController.js.map
  71992. var BABYLON;
  71993. (function (BABYLON) {
  71994. /**
  71995. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71996. */
  71997. var LoadedMeshInfo = /** @class */ (function () {
  71998. function LoadedMeshInfo() {
  71999. /**
  72000. * Map of the button meshes contained in the controller
  72001. */
  72002. this.buttonMeshes = {};
  72003. /**
  72004. * Map of the axis meshes contained in the controller
  72005. */
  72006. this.axisMeshes = {};
  72007. }
  72008. return LoadedMeshInfo;
  72009. }());
  72010. /**
  72011. * Defines the WindowsMotionController object that the state of the windows motion controller
  72012. */
  72013. var WindowsMotionController = /** @class */ (function (_super) {
  72014. __extends(WindowsMotionController, _super);
  72015. /**
  72016. * Creates a new WindowsMotionController from a gamepad
  72017. * @param vrGamepad the gamepad that the controller should be created from
  72018. */
  72019. function WindowsMotionController(vrGamepad) {
  72020. var _this = _super.call(this, vrGamepad) || this;
  72021. _this._mapping = {
  72022. // Semantic button names
  72023. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72024. // A mapping of the button name to glTF model node name
  72025. // that should be transformed by button value.
  72026. buttonMeshNames: {
  72027. 'trigger': 'SELECT',
  72028. 'menu': 'MENU',
  72029. 'grip': 'GRASP',
  72030. 'thumbstick': 'THUMBSTICK_PRESS',
  72031. 'trackpad': 'TOUCHPAD_PRESS'
  72032. },
  72033. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72034. buttonObservableNames: {
  72035. 'trigger': 'onTriggerStateChangedObservable',
  72036. 'menu': 'onSecondaryButtonStateChangedObservable',
  72037. 'grip': 'onMainButtonStateChangedObservable',
  72038. 'thumbstick': 'onPadStateChangedObservable',
  72039. 'trackpad': 'onTrackpadChangedObservable'
  72040. },
  72041. // A mapping of the axis name to glTF model node name
  72042. // that should be transformed by axis value.
  72043. // This array mirrors the browserGamepad.axes array, such that
  72044. // the mesh corresponding to axis 0 is in this array index 0.
  72045. axisMeshNames: [
  72046. 'THUMBSTICK_X',
  72047. 'THUMBSTICK_Y',
  72048. 'TOUCHPAD_TOUCH_X',
  72049. 'TOUCHPAD_TOUCH_Y'
  72050. ],
  72051. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72052. };
  72053. /**
  72054. * Fired when the trackpad on this controller is clicked
  72055. */
  72056. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72057. /**
  72058. * Fired when the trackpad on this controller is modified
  72059. */
  72060. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72061. /**
  72062. * The current x and y values of this controller's trackpad
  72063. */
  72064. _this.trackpad = { x: 0, y: 0 };
  72065. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72066. _this._loadedMeshInfo = null;
  72067. return _this;
  72068. }
  72069. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72070. /**
  72071. * Fired when the trigger on this controller is modified
  72072. */
  72073. get: function () {
  72074. return this.onTriggerStateChangedObservable;
  72075. },
  72076. enumerable: true,
  72077. configurable: true
  72078. });
  72079. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72080. /**
  72081. * Fired when the menu button on this controller is modified
  72082. */
  72083. get: function () {
  72084. return this.onSecondaryButtonStateChangedObservable;
  72085. },
  72086. enumerable: true,
  72087. configurable: true
  72088. });
  72089. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72090. /**
  72091. * Fired when the grip button on this controller is modified
  72092. */
  72093. get: function () {
  72094. return this.onMainButtonStateChangedObservable;
  72095. },
  72096. enumerable: true,
  72097. configurable: true
  72098. });
  72099. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72100. /**
  72101. * Fired when the thumbstick button on this controller is modified
  72102. */
  72103. get: function () {
  72104. return this.onPadStateChangedObservable;
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72110. /**
  72111. * Fired when the touchpad button on this controller is modified
  72112. */
  72113. get: function () {
  72114. return this.onTrackpadChangedObservable;
  72115. },
  72116. enumerable: true,
  72117. configurable: true
  72118. });
  72119. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72120. /**
  72121. * Fired when the touchpad values on this controller are modified
  72122. */
  72123. get: function () {
  72124. return this.onTrackpadValuesChangedObservable;
  72125. },
  72126. enumerable: true,
  72127. configurable: true
  72128. });
  72129. WindowsMotionController.prototype._updateTrackpad = function () {
  72130. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72131. this.trackpad.x = this.browserGamepad["axes"][2];
  72132. this.trackpad.y = this.browserGamepad["axes"][3];
  72133. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72134. }
  72135. };
  72136. /**
  72137. * Called once per frame by the engine.
  72138. */
  72139. WindowsMotionController.prototype.update = function () {
  72140. _super.prototype.update.call(this);
  72141. if (this.browserGamepad.axes) {
  72142. this._updateTrackpad();
  72143. // Only need to animate axes if there is a loaded mesh
  72144. if (this._loadedMeshInfo) {
  72145. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72146. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72147. }
  72148. }
  72149. }
  72150. };
  72151. /**
  72152. * Called once for each button that changed state since the last frame
  72153. * @param buttonIdx Which button index changed
  72154. * @param state New state of the button
  72155. * @param changes Which properties on the state changed since last frame
  72156. */
  72157. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72158. var buttonName = this._mapping.buttons[buttonIdx];
  72159. if (!buttonName) {
  72160. return;
  72161. }
  72162. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72163. this._updateTrackpad();
  72164. // Only emit events for buttons that we know how to map from index to name
  72165. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72166. if (observable) {
  72167. observable.notifyObservers(state);
  72168. }
  72169. this._lerpButtonTransform(buttonName, state.value);
  72170. };
  72171. /**
  72172. * Moves the buttons on the controller mesh based on their current state
  72173. * @param buttonName the name of the button to move
  72174. * @param buttonValue the value of the button which determines the buttons new position
  72175. */
  72176. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72177. // If there is no loaded mesh, there is nothing to transform.
  72178. if (!this._loadedMeshInfo) {
  72179. return;
  72180. }
  72181. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72182. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72183. return;
  72184. }
  72185. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72186. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72187. };
  72188. /**
  72189. * Moves the axis on the controller mesh based on its current state
  72190. * @param axis the index of the axis
  72191. * @param axisValue the value of the axis which determines the meshes new position
  72192. * @hidden
  72193. */
  72194. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72195. if (!this._loadedMeshInfo) {
  72196. return;
  72197. }
  72198. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72199. if (!meshInfo) {
  72200. return;
  72201. }
  72202. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72203. return;
  72204. }
  72205. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72206. var lerpValue = axisValue * 0.5 + 0.5;
  72207. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72208. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72209. };
  72210. /**
  72211. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72212. * @param scene scene in which to add meshes
  72213. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72214. */
  72215. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72216. var _this = this;
  72217. if (forceDefault === void 0) { forceDefault = false; }
  72218. var path;
  72219. var filename;
  72220. // Checking if GLB loader is present
  72221. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72222. // Determine the device specific folder based on the ID suffix
  72223. var device = 'default';
  72224. if (this.id && !forceDefault) {
  72225. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72226. device = ((match && match[0]) || device);
  72227. }
  72228. // Hand
  72229. if (this.hand === 'left') {
  72230. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72231. }
  72232. else { // Right is the default if no hand is specified
  72233. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72234. }
  72235. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72236. }
  72237. else {
  72238. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72239. path = BABYLON.GenericController.MODEL_BASE_URL;
  72240. filename = BABYLON.GenericController.MODEL_FILENAME;
  72241. }
  72242. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72243. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72244. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72245. if (!_this._loadedMeshInfo) {
  72246. return;
  72247. }
  72248. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72249. _this.attachToMesh(_this._defaultModel);
  72250. if (meshLoaded) {
  72251. meshLoaded(_this._defaultModel);
  72252. }
  72253. }, null, function (scene, message) {
  72254. BABYLON.Tools.Log(message);
  72255. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72256. if (!forceDefault) {
  72257. _this.initControllerMesh(scene, meshLoaded, true);
  72258. }
  72259. });
  72260. };
  72261. /**
  72262. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72263. * can be transformed by button presses and axes values, based on this._mapping.
  72264. *
  72265. * @param scene scene in which the meshes exist
  72266. * @param meshes list of meshes that make up the controller model to process
  72267. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72268. */
  72269. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72270. var loadedMeshInfo = null;
  72271. // Create a new mesh to contain the glTF hierarchy
  72272. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72273. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72274. var childMesh = null;
  72275. for (var i = 0; i < meshes.length; i++) {
  72276. var mesh = meshes[i];
  72277. if (!mesh.parent) {
  72278. // Exclude controller meshes from picking results
  72279. mesh.isPickable = false;
  72280. // Handle root node, attach to the new parentMesh
  72281. childMesh = mesh;
  72282. break;
  72283. }
  72284. }
  72285. if (childMesh) {
  72286. childMesh.setParent(parentMesh);
  72287. // Create our mesh info. Note that this method will always return non-null.
  72288. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72289. }
  72290. else {
  72291. BABYLON.Tools.Warn('Could not find root node in model file.');
  72292. }
  72293. return loadedMeshInfo;
  72294. };
  72295. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72296. var loadedMeshInfo = new LoadedMeshInfo();
  72297. var i;
  72298. loadedMeshInfo.rootNode = rootNode;
  72299. // Reset the caches
  72300. loadedMeshInfo.buttonMeshes = {};
  72301. loadedMeshInfo.axisMeshes = {};
  72302. // Button Meshes
  72303. for (i = 0; i < this._mapping.buttons.length; i++) {
  72304. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72305. if (!buttonMeshName) {
  72306. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72307. continue;
  72308. }
  72309. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72310. if (!buttonMesh) {
  72311. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72312. continue;
  72313. }
  72314. var buttonMeshInfo = {
  72315. index: i,
  72316. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72317. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72318. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72319. };
  72320. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72321. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72322. }
  72323. else {
  72324. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72325. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72326. '(VALUE: ' + !!buttonMeshInfo.value +
  72327. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72328. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72329. ')');
  72330. }
  72331. }
  72332. // Axis Meshes
  72333. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72334. var axisMeshName = this._mapping.axisMeshNames[i];
  72335. if (!axisMeshName) {
  72336. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72337. continue;
  72338. }
  72339. var axisMesh = getChildByName(rootNode, axisMeshName);
  72340. if (!axisMesh) {
  72341. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72342. continue;
  72343. }
  72344. var axisMeshInfo = {
  72345. index: i,
  72346. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72347. min: getImmediateChildByName(axisMesh, 'MIN'),
  72348. max: getImmediateChildByName(axisMesh, 'MAX')
  72349. };
  72350. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72351. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72352. }
  72353. else {
  72354. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72355. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72356. '(VALUE: ' + !!axisMeshInfo.value +
  72357. ', MIN: ' + !!axisMeshInfo.min +
  72358. ', MAX:' + !!axisMeshInfo.max +
  72359. ')');
  72360. }
  72361. }
  72362. // Pointing Ray
  72363. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72364. if (!loadedMeshInfo.pointingPoseNode) {
  72365. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72366. }
  72367. else {
  72368. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72369. }
  72370. return loadedMeshInfo;
  72371. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72372. function getChildByName(node, name) {
  72373. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72374. }
  72375. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72376. function getImmediateChildByName(node, name) {
  72377. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72378. }
  72379. };
  72380. /**
  72381. * Gets the ray of the controller in the direction the controller is pointing
  72382. * @param length the length the resulting ray should be
  72383. * @returns a ray in the direction the controller is pointing
  72384. */
  72385. WindowsMotionController.prototype.getForwardRay = function (length) {
  72386. if (length === void 0) { length = 100; }
  72387. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72388. return _super.prototype.getForwardRay.call(this, length);
  72389. }
  72390. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72391. var origin = m.getTranslation();
  72392. var forward = new BABYLON.Vector3(0, 0, -1);
  72393. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72394. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72395. return new BABYLON.Ray(origin, direction, length);
  72396. };
  72397. /**
  72398. * Disposes of the controller
  72399. */
  72400. WindowsMotionController.prototype.dispose = function () {
  72401. _super.prototype.dispose.call(this);
  72402. this.onTrackpadChangedObservable.clear();
  72403. };
  72404. /**
  72405. * The base url used to load the left and right controller models
  72406. */
  72407. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72408. /**
  72409. * The name of the left controller model file
  72410. */
  72411. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72412. /**
  72413. * The name of the right controller model file
  72414. */
  72415. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72416. /**
  72417. * The controller name prefix for this controller type
  72418. */
  72419. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72420. /**
  72421. * The controller id pattern for this controller type
  72422. */
  72423. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72424. return WindowsMotionController;
  72425. }(BABYLON.WebVRController));
  72426. BABYLON.WindowsMotionController = WindowsMotionController;
  72427. })(BABYLON || (BABYLON = {}));
  72428. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72429. var BABYLON;
  72430. (function (BABYLON) {
  72431. /**
  72432. * Gear VR Controller
  72433. */
  72434. var GearVRController = /** @class */ (function (_super) {
  72435. __extends(GearVRController, _super);
  72436. /**
  72437. * Creates a new GearVRController from a gamepad
  72438. * @param vrGamepad the gamepad that the controller should be created from
  72439. */
  72440. function GearVRController(vrGamepad) {
  72441. var _this = _super.call(this, vrGamepad) || this;
  72442. _this._buttonIndexToObservableNameMap = [
  72443. 'onTrackpadChangedObservable',
  72444. 'onTriggerStateChangedObservable' // Trigger
  72445. ];
  72446. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72447. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72448. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72449. return _this;
  72450. }
  72451. /**
  72452. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72453. * @param scene scene in which to add meshes
  72454. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72455. */
  72456. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72457. var _this = this;
  72458. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72459. _this._defaultModel = newMeshes[1];
  72460. _this.attachToMesh(_this._defaultModel);
  72461. if (meshLoaded) {
  72462. meshLoaded(_this._defaultModel);
  72463. }
  72464. });
  72465. };
  72466. /**
  72467. * Called once for each button that changed state since the last frame
  72468. * @param buttonIdx Which button index changed
  72469. * @param state New state of the button
  72470. * @param changes Which properties on the state changed since last frame
  72471. */
  72472. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72473. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72474. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72475. // Only emit events for buttons that we know how to map from index to observable
  72476. var observable = this[observableName];
  72477. if (observable) {
  72478. observable.notifyObservers(state);
  72479. }
  72480. }
  72481. };
  72482. /**
  72483. * Base Url for the controller model.
  72484. */
  72485. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72486. /**
  72487. * File name for the controller model.
  72488. */
  72489. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72490. /**
  72491. * Gamepad Id prefix used to identify this controller.
  72492. */
  72493. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72494. return GearVRController;
  72495. }(BABYLON.WebVRController));
  72496. BABYLON.GearVRController = GearVRController;
  72497. })(BABYLON || (BABYLON = {}));
  72498. //# sourceMappingURL=babylon.gearVRController.js.map
  72499. var BABYLON;
  72500. (function (BABYLON) {
  72501. /**
  72502. * Google Daydream controller
  72503. */
  72504. var DaydreamController = /** @class */ (function (_super) {
  72505. __extends(DaydreamController, _super);
  72506. /**
  72507. * Creates a new DaydreamController from a gamepad
  72508. * @param vrGamepad the gamepad that the controller should be created from
  72509. */
  72510. function DaydreamController(vrGamepad) {
  72511. var _this = _super.call(this, vrGamepad) || this;
  72512. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72513. return _this;
  72514. }
  72515. /**
  72516. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72517. * @param scene scene in which to add meshes
  72518. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72519. */
  72520. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72521. var _this = this;
  72522. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72523. _this._defaultModel = newMeshes[1];
  72524. _this.attachToMesh(_this._defaultModel);
  72525. if (meshLoaded) {
  72526. meshLoaded(_this._defaultModel);
  72527. }
  72528. });
  72529. };
  72530. /**
  72531. * Called once for each button that changed state since the last frame
  72532. * @param buttonIdx Which button index changed
  72533. * @param state New state of the button
  72534. * @param changes Which properties on the state changed since last frame
  72535. */
  72536. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72537. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72538. if (buttonIdx === 0) {
  72539. var observable = this.onTriggerStateChangedObservable;
  72540. if (observable) {
  72541. observable.notifyObservers(state);
  72542. }
  72543. }
  72544. else {
  72545. // If the app or home buttons are ever made available
  72546. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72547. }
  72548. };
  72549. /**
  72550. * Base Url for the controller model.
  72551. */
  72552. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72553. /**
  72554. * File name for the controller model.
  72555. */
  72556. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72557. /**
  72558. * Gamepad Id prefix used to identify Daydream Controller.
  72559. */
  72560. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72561. return DaydreamController;
  72562. }(BABYLON.WebVRController));
  72563. BABYLON.DaydreamController = DaydreamController;
  72564. })(BABYLON || (BABYLON = {}));
  72565. //# sourceMappingURL=babylon.daydreamController.js.map
  72566. var BABYLON;
  72567. (function (BABYLON) {
  72568. var FollowCamera = /** @class */ (function (_super) {
  72569. __extends(FollowCamera, _super);
  72570. function FollowCamera(name, position, scene, lockedTarget) {
  72571. if (lockedTarget === void 0) { lockedTarget = null; }
  72572. var _this = _super.call(this, name, position, scene) || this;
  72573. _this.radius = 12;
  72574. _this.rotationOffset = 0;
  72575. _this.heightOffset = 4;
  72576. _this.cameraAcceleration = 0.05;
  72577. _this.maxCameraSpeed = 20;
  72578. _this.lockedTarget = lockedTarget;
  72579. return _this;
  72580. }
  72581. FollowCamera.prototype.getRadians = function (degrees) {
  72582. return degrees * Math.PI / 180;
  72583. };
  72584. FollowCamera.prototype.follow = function (cameraTarget) {
  72585. if (!cameraTarget)
  72586. return;
  72587. var yRotation;
  72588. if (cameraTarget.rotationQuaternion) {
  72589. var rotMatrix = new BABYLON.Matrix();
  72590. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72591. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72592. }
  72593. else {
  72594. yRotation = cameraTarget.rotation.y;
  72595. }
  72596. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72597. var targetPosition = cameraTarget.getAbsolutePosition();
  72598. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72599. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72600. var dx = targetX - this.position.x;
  72601. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72602. var dz = (targetZ) - this.position.z;
  72603. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72604. var vy = dy * this.cameraAcceleration;
  72605. var vz = dz * this.cameraAcceleration * 2;
  72606. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72607. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72608. }
  72609. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72610. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72611. }
  72612. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72613. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72614. }
  72615. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72616. this.setTarget(targetPosition);
  72617. };
  72618. FollowCamera.prototype._checkInputs = function () {
  72619. _super.prototype._checkInputs.call(this);
  72620. if (this.lockedTarget) {
  72621. this.follow(this.lockedTarget);
  72622. }
  72623. };
  72624. FollowCamera.prototype.getClassName = function () {
  72625. return "FollowCamera";
  72626. };
  72627. __decorate([
  72628. BABYLON.serialize()
  72629. ], FollowCamera.prototype, "radius", void 0);
  72630. __decorate([
  72631. BABYLON.serialize()
  72632. ], FollowCamera.prototype, "rotationOffset", void 0);
  72633. __decorate([
  72634. BABYLON.serialize()
  72635. ], FollowCamera.prototype, "heightOffset", void 0);
  72636. __decorate([
  72637. BABYLON.serialize()
  72638. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72639. __decorate([
  72640. BABYLON.serialize()
  72641. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72642. __decorate([
  72643. BABYLON.serializeAsMeshReference("lockedTargetId")
  72644. ], FollowCamera.prototype, "lockedTarget", void 0);
  72645. return FollowCamera;
  72646. }(BABYLON.TargetCamera));
  72647. BABYLON.FollowCamera = FollowCamera;
  72648. var ArcFollowCamera = /** @class */ (function (_super) {
  72649. __extends(ArcFollowCamera, _super);
  72650. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72651. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72652. _this.alpha = alpha;
  72653. _this.beta = beta;
  72654. _this.radius = radius;
  72655. _this.target = target;
  72656. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72657. _this.follow();
  72658. return _this;
  72659. }
  72660. ArcFollowCamera.prototype.follow = function () {
  72661. if (!this.target) {
  72662. return;
  72663. }
  72664. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72665. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72666. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72667. var targetPosition = this.target.getAbsolutePosition();
  72668. this.position = targetPosition.add(this._cartesianCoordinates);
  72669. this.setTarget(targetPosition);
  72670. };
  72671. ArcFollowCamera.prototype._checkInputs = function () {
  72672. _super.prototype._checkInputs.call(this);
  72673. this.follow();
  72674. };
  72675. ArcFollowCamera.prototype.getClassName = function () {
  72676. return "ArcFollowCamera";
  72677. };
  72678. return ArcFollowCamera;
  72679. }(BABYLON.TargetCamera));
  72680. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72681. })(BABYLON || (BABYLON = {}));
  72682. //# sourceMappingURL=babylon.followCamera.js.map
  72683. var BABYLON;
  72684. (function (BABYLON) {
  72685. // We're mainly based on the logic defined into the FreeCamera code
  72686. var UniversalCamera = /** @class */ (function (_super) {
  72687. __extends(UniversalCamera, _super);
  72688. //-- end properties for backward compatibility for inputs
  72689. function UniversalCamera(name, position, scene) {
  72690. var _this = _super.call(this, name, position, scene) || this;
  72691. _this.inputs.addGamepad();
  72692. return _this;
  72693. }
  72694. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72695. //-- Begin properties for backward compatibility for inputs
  72696. get: function () {
  72697. var gamepad = this.inputs.attached["gamepad"];
  72698. if (gamepad)
  72699. return gamepad.gamepadAngularSensibility;
  72700. return 0;
  72701. },
  72702. set: function (value) {
  72703. var gamepad = this.inputs.attached["gamepad"];
  72704. if (gamepad)
  72705. gamepad.gamepadAngularSensibility = value;
  72706. },
  72707. enumerable: true,
  72708. configurable: true
  72709. });
  72710. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72711. get: function () {
  72712. var gamepad = this.inputs.attached["gamepad"];
  72713. if (gamepad)
  72714. return gamepad.gamepadMoveSensibility;
  72715. return 0;
  72716. },
  72717. set: function (value) {
  72718. var gamepad = this.inputs.attached["gamepad"];
  72719. if (gamepad)
  72720. gamepad.gamepadMoveSensibility = value;
  72721. },
  72722. enumerable: true,
  72723. configurable: true
  72724. });
  72725. UniversalCamera.prototype.getClassName = function () {
  72726. return "UniversalCamera";
  72727. };
  72728. return UniversalCamera;
  72729. }(BABYLON.TouchCamera));
  72730. BABYLON.UniversalCamera = UniversalCamera;
  72731. })(BABYLON || (BABYLON = {}));
  72732. //# sourceMappingURL=babylon.universalCamera.js.map
  72733. var BABYLON;
  72734. (function (BABYLON) {
  72735. // We're mainly based on the logic defined into the FreeCamera code
  72736. var GamepadCamera = /** @class */ (function (_super) {
  72737. __extends(GamepadCamera, _super);
  72738. //-- end properties for backward compatibility for inputs
  72739. function GamepadCamera(name, position, scene) {
  72740. return _super.call(this, name, position, scene) || this;
  72741. }
  72742. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72743. //-- Begin properties for backward compatibility for inputs
  72744. get: function () {
  72745. var gamepad = this.inputs.attached["gamepad"];
  72746. if (gamepad)
  72747. return gamepad.gamepadAngularSensibility;
  72748. return 0;
  72749. },
  72750. set: function (value) {
  72751. var gamepad = this.inputs.attached["gamepad"];
  72752. if (gamepad)
  72753. gamepad.gamepadAngularSensibility = value;
  72754. },
  72755. enumerable: true,
  72756. configurable: true
  72757. });
  72758. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72759. get: function () {
  72760. var gamepad = this.inputs.attached["gamepad"];
  72761. if (gamepad)
  72762. return gamepad.gamepadMoveSensibility;
  72763. return 0;
  72764. },
  72765. set: function (value) {
  72766. var gamepad = this.inputs.attached["gamepad"];
  72767. if (gamepad)
  72768. gamepad.gamepadMoveSensibility = value;
  72769. },
  72770. enumerable: true,
  72771. configurable: true
  72772. });
  72773. GamepadCamera.prototype.getClassName = function () {
  72774. return "GamepadCamera";
  72775. };
  72776. return GamepadCamera;
  72777. }(BABYLON.UniversalCamera));
  72778. BABYLON.GamepadCamera = GamepadCamera;
  72779. })(BABYLON || (BABYLON = {}));
  72780. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72781. var BABYLON;
  72782. (function (BABYLON) {
  72783. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72784. function PostProcessRenderPipelineManager() {
  72785. this._renderPipelines = {};
  72786. }
  72787. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72788. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72789. };
  72790. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72791. if (unique === void 0) { unique = false; }
  72792. var renderPipeline = this._renderPipelines[renderPipelineName];
  72793. if (!renderPipeline) {
  72794. return;
  72795. }
  72796. renderPipeline._attachCameras(cameras, unique);
  72797. };
  72798. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72799. var renderPipeline = this._renderPipelines[renderPipelineName];
  72800. if (!renderPipeline) {
  72801. return;
  72802. }
  72803. renderPipeline._detachCameras(cameras);
  72804. };
  72805. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72806. var renderPipeline = this._renderPipelines[renderPipelineName];
  72807. if (!renderPipeline) {
  72808. return;
  72809. }
  72810. renderPipeline._enableEffect(renderEffectName, cameras);
  72811. };
  72812. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72813. var renderPipeline = this._renderPipelines[renderPipelineName];
  72814. if (!renderPipeline) {
  72815. return;
  72816. }
  72817. renderPipeline._disableEffect(renderEffectName, cameras);
  72818. };
  72819. PostProcessRenderPipelineManager.prototype.update = function () {
  72820. for (var renderPipelineName in this._renderPipelines) {
  72821. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72822. var pipeline = this._renderPipelines[renderPipelineName];
  72823. if (!pipeline.isSupported) {
  72824. pipeline.dispose();
  72825. delete this._renderPipelines[renderPipelineName];
  72826. }
  72827. else {
  72828. pipeline._update();
  72829. }
  72830. }
  72831. }
  72832. };
  72833. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72834. for (var renderPipelineName in this._renderPipelines) {
  72835. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72836. var pipeline = this._renderPipelines[renderPipelineName];
  72837. pipeline._rebuild();
  72838. }
  72839. }
  72840. };
  72841. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72842. for (var renderPipelineName in this._renderPipelines) {
  72843. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72844. var pipeline = this._renderPipelines[renderPipelineName];
  72845. pipeline.dispose();
  72846. }
  72847. }
  72848. };
  72849. return PostProcessRenderPipelineManager;
  72850. }());
  72851. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72852. })(BABYLON || (BABYLON = {}));
  72853. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72854. var BABYLON;
  72855. (function (BABYLON) {
  72856. /**
  72857. * This represents a set of one or more post processes in Babylon.
  72858. * A post process can be used to apply a shader to a texture after it is rendered.
  72859. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72860. */
  72861. var PostProcessRenderEffect = /** @class */ (function () {
  72862. /**
  72863. * Instantiates a post process render effect.
  72864. * A post process can be used to apply a shader to a texture after it is rendered.
  72865. * @param engine The engine the effect is tied to
  72866. * @param name The name of the effect
  72867. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72868. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72869. */
  72870. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72871. this._name = name;
  72872. this._singleInstance = singleInstance || true;
  72873. this._getPostProcesses = getPostProcesses;
  72874. this._cameras = {};
  72875. this._indicesForCamera = {};
  72876. this._postProcesses = {};
  72877. }
  72878. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72879. /**
  72880. * Checks if all the post processes in the effect are supported.
  72881. */
  72882. get: function () {
  72883. for (var index in this._postProcesses) {
  72884. if (this._postProcesses.hasOwnProperty(index)) {
  72885. var pps = this._postProcesses[index];
  72886. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72887. if (!pps[ppIndex].isSupported) {
  72888. return false;
  72889. }
  72890. }
  72891. }
  72892. }
  72893. return true;
  72894. },
  72895. enumerable: true,
  72896. configurable: true
  72897. });
  72898. /**
  72899. * Updates the current state of the effect
  72900. */
  72901. PostProcessRenderEffect.prototype._update = function () {
  72902. };
  72903. /**
  72904. * Attaches the effect on cameras
  72905. * @param cameras The camera to attach to.
  72906. */
  72907. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72908. var _this = this;
  72909. var cameraKey;
  72910. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72911. if (!cams) {
  72912. return;
  72913. }
  72914. for (var i = 0; i < cams.length; i++) {
  72915. var camera = cams[i];
  72916. var cameraName = camera.name;
  72917. if (this._singleInstance) {
  72918. cameraKey = 0;
  72919. }
  72920. else {
  72921. cameraKey = cameraName;
  72922. }
  72923. if (!this._postProcesses[cameraKey]) {
  72924. var postProcess = this._getPostProcesses();
  72925. if (postProcess) {
  72926. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72927. }
  72928. }
  72929. if (!this._indicesForCamera[cameraName]) {
  72930. this._indicesForCamera[cameraName] = [];
  72931. }
  72932. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72933. var index = camera.attachPostProcess(postProcess);
  72934. _this._indicesForCamera[cameraName].push(index);
  72935. });
  72936. if (!this._cameras[cameraName]) {
  72937. this._cameras[cameraName] = camera;
  72938. }
  72939. }
  72940. };
  72941. /**
  72942. * Detatches the effect on cameras
  72943. * @param cameras The camera to detatch from.
  72944. */
  72945. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72946. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72947. if (!cams) {
  72948. return;
  72949. }
  72950. for (var i = 0; i < cams.length; i++) {
  72951. var camera = cams[i];
  72952. var cameraName = camera.name;
  72953. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72954. camera.detachPostProcess(postProcess);
  72955. });
  72956. if (this._cameras[cameraName]) {
  72957. //this._indicesForCamera.splice(index, 1);
  72958. this._cameras[cameraName] = null;
  72959. }
  72960. }
  72961. };
  72962. /**
  72963. * Enables the effect on given cameras
  72964. * @param cameras The camera to enable.
  72965. */
  72966. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72967. var _this = this;
  72968. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72969. if (!cams) {
  72970. return;
  72971. }
  72972. for (var i = 0; i < cams.length; i++) {
  72973. var camera = cams[i];
  72974. var cameraName = camera.name;
  72975. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72976. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72977. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72978. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72979. });
  72980. }
  72981. }
  72982. }
  72983. };
  72984. /**
  72985. * Disables the effect on the given cameras
  72986. * @param cameras The camera to disable.
  72987. */
  72988. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72989. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72990. if (!cams) {
  72991. return;
  72992. }
  72993. for (var i = 0; i < cams.length; i++) {
  72994. var camera = cams[i];
  72995. var cameraName = camera.name;
  72996. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72997. camera.detachPostProcess(postProcess);
  72998. });
  72999. }
  73000. };
  73001. /**
  73002. * Gets a list of the post processes contained in the effect.
  73003. * @param camera The camera to get the post processes on.
  73004. * @returns The list of the post processes in the effect.
  73005. */
  73006. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73007. if (this._singleInstance) {
  73008. return this._postProcesses[0];
  73009. }
  73010. else {
  73011. if (!camera) {
  73012. return null;
  73013. }
  73014. return this._postProcesses[camera.name];
  73015. }
  73016. };
  73017. return PostProcessRenderEffect;
  73018. }());
  73019. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73020. })(BABYLON || (BABYLON = {}));
  73021. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73022. var BABYLON;
  73023. (function (BABYLON) {
  73024. var PostProcessRenderPipeline = /** @class */ (function () {
  73025. function PostProcessRenderPipeline(engine, name) {
  73026. this.engine = engine;
  73027. this._name = name;
  73028. this._renderEffects = {};
  73029. this._renderEffectsForIsolatedPass = new Array();
  73030. this._cameras = [];
  73031. }
  73032. PostProcessRenderPipeline.prototype.getClassName = function () {
  73033. return "PostProcessRenderPipeline";
  73034. };
  73035. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73036. get: function () {
  73037. for (var renderEffectName in this._renderEffects) {
  73038. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73039. if (!this._renderEffects[renderEffectName].isSupported) {
  73040. return false;
  73041. }
  73042. }
  73043. }
  73044. return true;
  73045. },
  73046. enumerable: true,
  73047. configurable: true
  73048. });
  73049. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73050. this._renderEffects[renderEffect._name] = renderEffect;
  73051. };
  73052. // private
  73053. PostProcessRenderPipeline.prototype._rebuild = function () {
  73054. };
  73055. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73056. var renderEffects = this._renderEffects[renderEffectName];
  73057. if (!renderEffects) {
  73058. return;
  73059. }
  73060. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73061. };
  73062. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73063. var renderEffects = this._renderEffects[renderEffectName];
  73064. if (!renderEffects) {
  73065. return;
  73066. }
  73067. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73068. };
  73069. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73070. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73071. if (!cams) {
  73072. return;
  73073. }
  73074. var indicesToDelete = [];
  73075. var i;
  73076. for (i = 0; i < cams.length; i++) {
  73077. var camera = cams[i];
  73078. var cameraName = camera.name;
  73079. if (this._cameras.indexOf(camera) === -1) {
  73080. this._cameras[cameraName] = camera;
  73081. }
  73082. else if (unique) {
  73083. indicesToDelete.push(i);
  73084. }
  73085. }
  73086. for (i = 0; i < indicesToDelete.length; i++) {
  73087. cameras.splice(indicesToDelete[i], 1);
  73088. }
  73089. for (var renderEffectName in this._renderEffects) {
  73090. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73091. this._renderEffects[renderEffectName]._attachCameras(cams);
  73092. }
  73093. }
  73094. };
  73095. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73096. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73097. if (!cams) {
  73098. return;
  73099. }
  73100. for (var renderEffectName in this._renderEffects) {
  73101. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73102. this._renderEffects[renderEffectName]._detachCameras(cams);
  73103. }
  73104. }
  73105. for (var i = 0; i < cams.length; i++) {
  73106. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73107. }
  73108. };
  73109. PostProcessRenderPipeline.prototype._update = function () {
  73110. for (var renderEffectName in this._renderEffects) {
  73111. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73112. this._renderEffects[renderEffectName]._update();
  73113. }
  73114. }
  73115. for (var i = 0; i < this._cameras.length; i++) {
  73116. var cameraName = this._cameras[i].name;
  73117. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73118. this._renderEffectsForIsolatedPass[cameraName]._update();
  73119. }
  73120. }
  73121. };
  73122. PostProcessRenderPipeline.prototype._reset = function () {
  73123. this._renderEffects = {};
  73124. this._renderEffectsForIsolatedPass = new Array();
  73125. };
  73126. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73127. // 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)
  73128. var effectKeys = Object.keys(this._renderEffects);
  73129. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73130. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73131. if (postProcesses) {
  73132. postProcesses[0].samples = sampleCount;
  73133. return true;
  73134. }
  73135. }
  73136. return false;
  73137. };
  73138. PostProcessRenderPipeline.prototype.dispose = function () {
  73139. // Must be implemented by children
  73140. };
  73141. __decorate([
  73142. BABYLON.serialize()
  73143. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73144. return PostProcessRenderPipeline;
  73145. }());
  73146. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73147. })(BABYLON || (BABYLON = {}));
  73148. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73149. var BABYLON;
  73150. (function (BABYLON) {
  73151. /**
  73152. * This represents a depth renderer in Babylon.
  73153. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73154. */
  73155. var DepthRenderer = /** @class */ (function () {
  73156. /**
  73157. * Instantiates a depth renderer
  73158. * @param scene The scene the renderer belongs to
  73159. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73160. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73161. */
  73162. function DepthRenderer(scene, type, camera) {
  73163. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73164. if (camera === void 0) { camera = null; }
  73165. var _this = this;
  73166. this._scene = scene;
  73167. this._camera = camera;
  73168. var engine = scene.getEngine();
  73169. // Render target
  73170. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73171. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73172. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73173. this._depthMap.refreshRate = 1;
  73174. this._depthMap.renderParticles = false;
  73175. this._depthMap.renderList = null;
  73176. // Camera to get depth map from to support multiple concurrent cameras
  73177. this._depthMap.activeCamera = this._camera;
  73178. this._depthMap.ignoreCameraViewport = true;
  73179. this._depthMap.useCameraPostProcesses = false;
  73180. // set default depth value to 1.0 (far away)
  73181. this._depthMap.onClearObservable.add(function (engine) {
  73182. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73183. });
  73184. // Custom render function
  73185. var renderSubMesh = function (subMesh) {
  73186. var mesh = subMesh.getRenderingMesh();
  73187. var scene = _this._scene;
  73188. var engine = scene.getEngine();
  73189. var material = subMesh.getMaterial();
  73190. if (!material) {
  73191. return;
  73192. }
  73193. // Culling and reverse (right handed system)
  73194. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73195. // Managing instances
  73196. var batch = mesh._getInstancesRenderList(subMesh._id);
  73197. if (batch.mustReturn) {
  73198. return;
  73199. }
  73200. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73201. var camera = _this._camera || scene.activeCamera;
  73202. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73203. engine.enableEffect(_this._effect);
  73204. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73205. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73206. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73207. // Alpha test
  73208. if (material && material.needAlphaTesting()) {
  73209. var alphaTexture = material.getAlphaTestTexture();
  73210. if (alphaTexture) {
  73211. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73212. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73213. }
  73214. }
  73215. // Bones
  73216. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73217. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73218. }
  73219. // Draw
  73220. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73221. }
  73222. };
  73223. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73224. var index;
  73225. if (depthOnlySubMeshes.length) {
  73226. engine.setColorWrite(false);
  73227. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73228. renderSubMesh(depthOnlySubMeshes.data[index]);
  73229. }
  73230. engine.setColorWrite(true);
  73231. }
  73232. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73233. renderSubMesh(opaqueSubMeshes.data[index]);
  73234. }
  73235. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73236. renderSubMesh(alphaTestSubMeshes.data[index]);
  73237. }
  73238. };
  73239. }
  73240. /**
  73241. * Creates the depth rendering effect and checks if the effect is ready.
  73242. * @param subMesh The submesh to be used to render the depth map of
  73243. * @param useInstances If multiple world instances should be used
  73244. * @returns if the depth renderer is ready to render the depth map
  73245. */
  73246. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73247. var material = subMesh.getMaterial();
  73248. if (material.disableDepthWrite) {
  73249. return false;
  73250. }
  73251. var defines = [];
  73252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73253. var mesh = subMesh.getMesh();
  73254. // Alpha test
  73255. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73256. defines.push("#define ALPHATEST");
  73257. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73258. attribs.push(BABYLON.VertexBuffer.UVKind);
  73259. defines.push("#define UV1");
  73260. }
  73261. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73262. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73263. defines.push("#define UV2");
  73264. }
  73265. }
  73266. // Bones
  73267. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73270. if (mesh.numBoneInfluencers > 4) {
  73271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73273. }
  73274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73275. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73276. }
  73277. else {
  73278. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73279. }
  73280. // Instances
  73281. if (useInstances) {
  73282. defines.push("#define INSTANCES");
  73283. attribs.push("world0");
  73284. attribs.push("world1");
  73285. attribs.push("world2");
  73286. attribs.push("world3");
  73287. }
  73288. // Get correct effect
  73289. var join = defines.join("\n");
  73290. if (this._cachedDefines !== join) {
  73291. this._cachedDefines = join;
  73292. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73293. }
  73294. return this._effect.isReady();
  73295. };
  73296. /**
  73297. * Gets the texture which the depth map will be written to.
  73298. * @returns The depth map texture
  73299. */
  73300. DepthRenderer.prototype.getDepthMap = function () {
  73301. return this._depthMap;
  73302. };
  73303. /**
  73304. * Disposes of the depth renderer.
  73305. */
  73306. DepthRenderer.prototype.dispose = function () {
  73307. this._depthMap.dispose();
  73308. };
  73309. return DepthRenderer;
  73310. }());
  73311. BABYLON.DepthRenderer = DepthRenderer;
  73312. })(BABYLON || (BABYLON = {}));
  73313. //# sourceMappingURL=babylon.depthRenderer.js.map
  73314. var BABYLON;
  73315. (function (BABYLON) {
  73316. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73317. __extends(SSAORenderingPipeline, _super);
  73318. /**
  73319. * @constructor
  73320. * @param {string} name - The rendering pipeline name
  73321. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73322. * @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 }
  73323. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73324. */
  73325. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73326. var _this = _super.call(this, scene.getEngine(), name) || this;
  73327. // Members
  73328. /**
  73329. * The PassPostProcess id in the pipeline that contains the original scene color
  73330. */
  73331. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73332. /**
  73333. * The SSAO PostProcess id in the pipeline
  73334. */
  73335. _this.SSAORenderEffect = "SSAORenderEffect";
  73336. /**
  73337. * The horizontal blur PostProcess id in the pipeline
  73338. */
  73339. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73340. /**
  73341. * The vertical blur PostProcess id in the pipeline
  73342. */
  73343. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73344. /**
  73345. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73346. */
  73347. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73348. /**
  73349. * The output strength of the SSAO post-process. Default value is 1.0.
  73350. */
  73351. _this.totalStrength = 1.0;
  73352. /**
  73353. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73354. */
  73355. _this.radius = 0.0001;
  73356. /**
  73357. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73358. * Must not be equal to fallOff and superior to fallOff.
  73359. * Default value is 0.975
  73360. */
  73361. _this.area = 0.0075;
  73362. /**
  73363. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73364. * Must not be equal to area and inferior to area.
  73365. * Default value is 0.0
  73366. */
  73367. _this.fallOff = 0.000001;
  73368. /**
  73369. * The base color of the SSAO post-process
  73370. * The final result is "base + ssao" between [0, 1]
  73371. */
  73372. _this.base = 0.5;
  73373. _this._firstUpdate = true;
  73374. _this._scene = scene;
  73375. // Set up assets
  73376. _this._createRandomTexture();
  73377. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73378. var ssaoRatio = ratio.ssaoRatio || ratio;
  73379. var combineRatio = ratio.combineRatio || ratio;
  73380. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73381. _this._createSSAOPostProcess(ssaoRatio);
  73382. _this._createBlurPostProcess(ssaoRatio);
  73383. _this._createSSAOCombinePostProcess(combineRatio);
  73384. // Set up pipeline
  73385. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73390. // Finish
  73391. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73392. if (cameras)
  73393. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73394. return _this;
  73395. }
  73396. // Public Methods
  73397. /**
  73398. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73399. */
  73400. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73401. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73402. for (var i = 0; i < this._scene.cameras.length; i++) {
  73403. var camera = this._scene.cameras[i];
  73404. this._originalColorPostProcess.dispose(camera);
  73405. this._ssaoPostProcess.dispose(camera);
  73406. this._blurHPostProcess.dispose(camera);
  73407. this._blurVPostProcess.dispose(camera);
  73408. this._ssaoCombinePostProcess.dispose(camera);
  73409. }
  73410. this._randomTexture.dispose();
  73411. if (disableDepthRender)
  73412. this._scene.disableDepthRenderer();
  73413. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73414. _super.prototype.dispose.call(this);
  73415. };
  73416. // Private Methods
  73417. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73418. var _this = this;
  73419. var size = 16;
  73420. 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);
  73421. 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);
  73422. this._blurHPostProcess.onActivateObservable.add(function () {
  73423. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73424. _this._blurHPostProcess.kernel = size * dw;
  73425. });
  73426. this._blurVPostProcess.onActivateObservable.add(function () {
  73427. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73428. _this._blurVPostProcess.kernel = size * dw;
  73429. });
  73430. };
  73431. SSAORenderingPipeline.prototype._rebuild = function () {
  73432. this._firstUpdate = true;
  73433. _super.prototype._rebuild.call(this);
  73434. };
  73435. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73436. var _this = this;
  73437. var numSamples = 16;
  73438. var sampleSphere = [
  73439. 0.5381, 0.1856, -0.4319,
  73440. 0.1379, 0.2486, 0.4430,
  73441. 0.3371, 0.5679, -0.0057,
  73442. -0.6999, -0.0451, -0.0019,
  73443. 0.0689, -0.1598, -0.8547,
  73444. 0.0560, 0.0069, -0.1843,
  73445. -0.0146, 0.1402, 0.0762,
  73446. 0.0100, -0.1924, -0.0344,
  73447. -0.3577, -0.5301, -0.4358,
  73448. -0.3169, 0.1063, 0.0158,
  73449. 0.0103, -0.5869, 0.0046,
  73450. -0.0897, -0.4940, 0.3287,
  73451. 0.7119, -0.0154, -0.0918,
  73452. -0.0533, 0.0596, -0.5411,
  73453. 0.0352, -0.0631, 0.5460,
  73454. -0.4776, 0.2847, -0.0271
  73455. ];
  73456. var samplesFactor = 1.0 / numSamples;
  73457. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73458. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73459. "area", "fallOff", "base", "range", "viewport"
  73460. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73461. this._ssaoPostProcess.onApply = function (effect) {
  73462. if (_this._firstUpdate) {
  73463. effect.setArray3("sampleSphere", sampleSphere);
  73464. effect.setFloat("samplesFactor", samplesFactor);
  73465. effect.setFloat("randTextureTiles", 4.0);
  73466. }
  73467. effect.setFloat("totalStrength", _this.totalStrength);
  73468. effect.setFloat("radius", _this.radius);
  73469. effect.setFloat("area", _this.area);
  73470. effect.setFloat("fallOff", _this.fallOff);
  73471. effect.setFloat("base", _this.base);
  73472. effect.setTexture("textureSampler", _this._depthTexture);
  73473. effect.setTexture("randomSampler", _this._randomTexture);
  73474. };
  73475. };
  73476. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73477. var _this = this;
  73478. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73479. this._ssaoCombinePostProcess.onApply = function (effect) {
  73480. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73481. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73482. };
  73483. };
  73484. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73485. var size = 512;
  73486. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73487. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73488. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73489. var context = this._randomTexture.getContext();
  73490. var rand = function (min, max) {
  73491. return Math.random() * (max - min) + min;
  73492. };
  73493. var randVector = BABYLON.Vector3.Zero();
  73494. for (var x = 0; x < size; x++) {
  73495. for (var y = 0; y < size; y++) {
  73496. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73497. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73498. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73499. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73500. context.fillRect(x, y, 1, 1);
  73501. }
  73502. }
  73503. this._randomTexture.update(false);
  73504. };
  73505. __decorate([
  73506. BABYLON.serialize()
  73507. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73508. __decorate([
  73509. BABYLON.serialize()
  73510. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73511. __decorate([
  73512. BABYLON.serialize()
  73513. ], SSAORenderingPipeline.prototype, "area", void 0);
  73514. __decorate([
  73515. BABYLON.serialize()
  73516. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73517. __decorate([
  73518. BABYLON.serialize()
  73519. ], SSAORenderingPipeline.prototype, "base", void 0);
  73520. return SSAORenderingPipeline;
  73521. }(BABYLON.PostProcessRenderPipeline));
  73522. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73523. })(BABYLON || (BABYLON = {}));
  73524. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73525. var BABYLON;
  73526. (function (BABYLON) {
  73527. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73528. __extends(SSAO2RenderingPipeline, _super);
  73529. /**
  73530. * @constructor
  73531. * @param {string} name - The rendering pipeline name
  73532. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73533. * @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 }
  73534. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73535. */
  73536. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73537. var _this = _super.call(this, scene.getEngine(), name) || this;
  73538. // Members
  73539. /**
  73540. * The PassPostProcess id in the pipeline that contains the original scene color
  73541. */
  73542. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73543. /**
  73544. * The SSAO PostProcess id in the pipeline
  73545. */
  73546. _this.SSAORenderEffect = "SSAORenderEffect";
  73547. /**
  73548. * The horizontal blur PostProcess id in the pipeline
  73549. */
  73550. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73551. /**
  73552. * The vertical blur PostProcess id in the pipeline
  73553. */
  73554. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73555. /**
  73556. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73557. */
  73558. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73559. /**
  73560. * The output strength of the SSAO post-process. Default value is 1.0.
  73561. */
  73562. _this.totalStrength = 1.0;
  73563. /**
  73564. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73565. */
  73566. _this.maxZ = 100.0;
  73567. /**
  73568. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73569. */
  73570. _this.minZAspect = 0.2;
  73571. /**
  73572. * Number of samples used for the SSAO calculations. Default value is 8
  73573. */
  73574. _this._samples = 8;
  73575. /**
  73576. * Are we using bilateral blur ?
  73577. */
  73578. _this._expensiveBlur = true;
  73579. /**
  73580. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73581. */
  73582. _this.radius = 2.0;
  73583. /**
  73584. * The base color of the SSAO post-process
  73585. * The final result is "base + ssao" between [0, 1]
  73586. */
  73587. _this.base = 0.1;
  73588. _this._firstUpdate = true;
  73589. _this._scene = scene;
  73590. _this._ratio = ratio;
  73591. if (!_this.isSupported) {
  73592. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73593. return _this;
  73594. }
  73595. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73596. var blurRatio = _this._ratio.blurRatio || ratio;
  73597. // Set up assets
  73598. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73599. _this._createRandomTexture();
  73600. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73601. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73602. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73603. _this._createSSAOPostProcess(1.0);
  73604. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73605. _this._createSSAOCombinePostProcess(blurRatio);
  73606. // Set up pipeline
  73607. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73608. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73609. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73610. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73612. // Finish
  73613. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73614. if (cameras)
  73615. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73616. return _this;
  73617. }
  73618. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73619. get: function () {
  73620. return this._samples;
  73621. },
  73622. set: function (n) {
  73623. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73624. this._samples = n;
  73625. this._sampleSphere = this._generateHemisphere();
  73626. this._firstUpdate = true;
  73627. },
  73628. enumerable: true,
  73629. configurable: true
  73630. });
  73631. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73632. get: function () {
  73633. return this._expensiveBlur;
  73634. },
  73635. set: function (b) {
  73636. 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"]);
  73637. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73638. this._expensiveBlur = b;
  73639. this._firstUpdate = true;
  73640. },
  73641. enumerable: true,
  73642. configurable: true
  73643. });
  73644. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73645. /**
  73646. * Support test.
  73647. */
  73648. get: function () {
  73649. var engine = BABYLON.Engine.LastCreatedEngine;
  73650. if (!engine) {
  73651. return false;
  73652. }
  73653. return engine.getCaps().drawBuffersExtension;
  73654. },
  73655. enumerable: true,
  73656. configurable: true
  73657. });
  73658. // Public Methods
  73659. /**
  73660. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73661. */
  73662. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73663. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73664. for (var i = 0; i < this._scene.cameras.length; i++) {
  73665. var camera = this._scene.cameras[i];
  73666. this._originalColorPostProcess.dispose(camera);
  73667. this._ssaoPostProcess.dispose(camera);
  73668. this._blurHPostProcess.dispose(camera);
  73669. this._blurVPostProcess.dispose(camera);
  73670. this._ssaoCombinePostProcess.dispose(camera);
  73671. }
  73672. this._randomTexture.dispose();
  73673. if (disableGeometryBufferRenderer)
  73674. this._scene.disableGeometryBufferRenderer();
  73675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73676. _super.prototype.dispose.call(this);
  73677. };
  73678. // Private Methods
  73679. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73680. var _this = this;
  73681. this._samplerOffsets = [];
  73682. var expensive = this.expensiveBlur;
  73683. for (var i = -8; i < 8; i++) {
  73684. this._samplerOffsets.push(i * 2 + 0.5);
  73685. }
  73686. 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");
  73687. this._blurHPostProcess.onApply = function (effect) {
  73688. if (!_this._scene.activeCamera) {
  73689. return;
  73690. }
  73691. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73692. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73693. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73694. effect.setFloat("radius", _this.radius);
  73695. effect.setTexture("depthSampler", _this._depthTexture);
  73696. if (_this._firstUpdate) {
  73697. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73698. }
  73699. };
  73700. 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");
  73701. this._blurVPostProcess.onApply = function (effect) {
  73702. if (!_this._scene.activeCamera) {
  73703. return;
  73704. }
  73705. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73706. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73707. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73708. effect.setFloat("radius", _this.radius);
  73709. effect.setTexture("depthSampler", _this._depthTexture);
  73710. if (_this._firstUpdate) {
  73711. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73712. _this._firstUpdate = false;
  73713. }
  73714. };
  73715. };
  73716. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73717. this._firstUpdate = true;
  73718. _super.prototype._rebuild.call(this);
  73719. };
  73720. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73721. var numSamples = this.samples;
  73722. var result = [];
  73723. var vector, scale;
  73724. var rand = function (min, max) {
  73725. return Math.random() * (max - min) + min;
  73726. };
  73727. var i = 0;
  73728. while (i < numSamples) {
  73729. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73730. vector.normalize();
  73731. scale = i / numSamples;
  73732. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73733. vector.scaleInPlace(scale);
  73734. result.push(vector.x, vector.y, vector.z);
  73735. i++;
  73736. }
  73737. return result;
  73738. };
  73739. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73740. var _this = this;
  73741. var numSamples = this.samples;
  73742. this._sampleSphere = this._generateHemisphere();
  73743. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73744. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73745. "base", "range", "projection", "near", "far", "texelSize",
  73746. "xViewport", "yViewport", "maxZ", "minZAspect"
  73747. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73748. this._ssaoPostProcess.onApply = function (effect) {
  73749. if (_this._firstUpdate) {
  73750. effect.setArray3("sampleSphere", _this._sampleSphere);
  73751. effect.setFloat("randTextureTiles", 4.0);
  73752. }
  73753. if (!_this._scene.activeCamera) {
  73754. return;
  73755. }
  73756. effect.setFloat("samplesFactor", 1 / _this.samples);
  73757. effect.setFloat("totalStrength", _this.totalStrength);
  73758. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73759. effect.setFloat("radius", _this.radius);
  73760. effect.setFloat("maxZ", _this.maxZ);
  73761. effect.setFloat("minZAspect", _this.minZAspect);
  73762. effect.setFloat("base", _this.base);
  73763. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73764. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73765. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73766. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73767. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73768. effect.setTexture("textureSampler", _this._depthTexture);
  73769. effect.setTexture("normalSampler", _this._normalTexture);
  73770. effect.setTexture("randomSampler", _this._randomTexture);
  73771. };
  73772. };
  73773. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73774. var _this = this;
  73775. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73776. this._ssaoCombinePostProcess.onApply = function (effect) {
  73777. var viewport = _this._scene.activeCamera.viewport;
  73778. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73779. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73780. };
  73781. };
  73782. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73783. var size = 512;
  73784. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73785. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73786. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73787. var context = this._randomTexture.getContext();
  73788. var rand = function (min, max) {
  73789. return Math.random() * (max - min) + min;
  73790. };
  73791. var randVector = BABYLON.Vector3.Zero();
  73792. for (var x = 0; x < size; x++) {
  73793. for (var y = 0; y < size; y++) {
  73794. randVector.x = rand(0.0, 1.0);
  73795. randVector.y = rand(0.0, 1.0);
  73796. randVector.z = 0.0;
  73797. randVector.normalize();
  73798. randVector.scaleInPlace(255);
  73799. randVector.x = Math.floor(randVector.x);
  73800. randVector.y = Math.floor(randVector.y);
  73801. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73802. context.fillRect(x, y, 1, 1);
  73803. }
  73804. }
  73805. this._randomTexture.update(false);
  73806. };
  73807. /**
  73808. * Serialize the rendering pipeline (Used when exporting)
  73809. * @returns the serialized object
  73810. */
  73811. SSAO2RenderingPipeline.prototype.serialize = function () {
  73812. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73813. serializationObject.customType = "SSAO2RenderingPipeline";
  73814. return serializationObject;
  73815. };
  73816. /**
  73817. * Parse the serialized pipeline
  73818. * @param source Source pipeline.
  73819. * @param scene The scene to load the pipeline to.
  73820. * @param rootUrl The URL of the serialized pipeline.
  73821. * @returns An instantiated pipeline from the serialized object.
  73822. */
  73823. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73824. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73825. };
  73826. __decorate([
  73827. BABYLON.serialize()
  73828. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73829. __decorate([
  73830. BABYLON.serialize()
  73831. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73832. __decorate([
  73833. BABYLON.serialize()
  73834. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73835. __decorate([
  73836. BABYLON.serialize("samples")
  73837. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73838. __decorate([
  73839. BABYLON.serialize()
  73840. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73841. __decorate([
  73842. BABYLON.serialize("expensiveBlur")
  73843. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73844. __decorate([
  73845. BABYLON.serialize()
  73846. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73847. __decorate([
  73848. BABYLON.serialize()
  73849. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73850. return SSAO2RenderingPipeline;
  73851. }(BABYLON.PostProcessRenderPipeline));
  73852. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73853. })(BABYLON || (BABYLON = {}));
  73854. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73855. // BABYLON.JS Chromatic Aberration GLSL Shader
  73856. // Author: Olivier Guyot
  73857. // Separates very slightly R, G and B colors on the edges of the screen
  73858. // Inspired by Francois Tarlier & Martins Upitis
  73859. var BABYLON;
  73860. (function (BABYLON) {
  73861. var LensRenderingPipeline = /** @class */ (function (_super) {
  73862. __extends(LensRenderingPipeline, _super);
  73863. /**
  73864. * @constructor
  73865. *
  73866. * Effect parameters are as follow:
  73867. * {
  73868. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73869. * edge_blur: number; // from 0 to x (1 for realism)
  73870. * distortion: number; // from 0 to x (1 for realism)
  73871. * grain_amount: number; // from 0 to 1
  73872. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73873. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73874. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73875. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73876. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73877. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73878. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73879. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73880. * }
  73881. * Note: if an effect parameter is unset, effect is disabled
  73882. *
  73883. * @param {string} name - The rendering pipeline name
  73884. * @param {object} parameters - An object containing all parameters (see above)
  73885. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73886. * @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)
  73887. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73888. */
  73889. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73890. if (ratio === void 0) { ratio = 1.0; }
  73891. var _this = _super.call(this, scene.getEngine(), name) || this;
  73892. // Lens effects can be of the following:
  73893. // - chromatic aberration (slight shift of RGB colors)
  73894. // - blur on the edge of the lens
  73895. // - lens distortion
  73896. // - depth-of-field blur & highlights enhancing
  73897. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73898. // - grain effect (noise or custom texture)
  73899. // Two additional texture samplers are needed:
  73900. // - depth map (for depth-of-field)
  73901. // - grain texture
  73902. /**
  73903. * The chromatic aberration PostProcess id in the pipeline
  73904. */
  73905. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73906. /**
  73907. * The highlights enhancing PostProcess id in the pipeline
  73908. */
  73909. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73910. /**
  73911. * The depth-of-field PostProcess id in the pipeline
  73912. */
  73913. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73914. _this._scene = scene;
  73915. // Fetch texture samplers
  73916. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73917. if (parameters.grain_texture) {
  73918. _this._grainTexture = parameters.grain_texture;
  73919. }
  73920. else {
  73921. _this._createGrainTexture();
  73922. }
  73923. // save parameters
  73924. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73925. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73926. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73927. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73928. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73929. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73930. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73931. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73932. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73933. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73934. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73935. // Create effects
  73936. _this._createChromaticAberrationPostProcess(ratio);
  73937. _this._createHighlightsPostProcess(ratio);
  73938. _this._createDepthOfFieldPostProcess(ratio / 4);
  73939. // Set up pipeline
  73940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73943. if (_this._highlightsGain === -1) {
  73944. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73945. }
  73946. // Finish
  73947. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73948. if (cameras) {
  73949. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73950. }
  73951. return _this;
  73952. }
  73953. // public methods (self explanatory)
  73954. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73955. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73956. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73957. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73958. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73959. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73960. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73961. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73962. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73963. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73964. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73965. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73966. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73967. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73968. };
  73969. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73970. this._highlightsPostProcess.updateEffect();
  73971. };
  73972. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73973. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73974. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73975. this._highlightsGain = amount;
  73976. };
  73977. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73978. if (this._highlightsGain === -1) {
  73979. this._highlightsGain = 1.0;
  73980. }
  73981. this._highlightsThreshold = amount;
  73982. };
  73983. LensRenderingPipeline.prototype.disableHighlights = function () {
  73984. this._highlightsGain = -1;
  73985. };
  73986. /**
  73987. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73988. */
  73989. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73990. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73991. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73992. this._chromaticAberrationPostProcess = null;
  73993. this._highlightsPostProcess = null;
  73994. this._depthOfFieldPostProcess = null;
  73995. this._grainTexture.dispose();
  73996. if (disableDepthRender)
  73997. this._scene.disableDepthRenderer();
  73998. };
  73999. // colors shifting and distortion
  74000. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74001. var _this = this;
  74002. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74003. [], // samplers
  74004. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74005. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74006. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74007. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74008. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74009. effect.setFloat('radialIntensity', 1);
  74010. effect.setFloat2('direction', 17, 17);
  74011. effect.setFloat2('centerPosition', 0.5, 0.5);
  74012. };
  74013. };
  74014. // highlights enhancing
  74015. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74016. var _this = this;
  74017. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74018. [], // samplers
  74019. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74020. this._highlightsPostProcess.onApply = function (effect) {
  74021. effect.setFloat('gain', _this._highlightsGain);
  74022. effect.setFloat('threshold', _this._highlightsThreshold);
  74023. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74024. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74025. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74026. };
  74027. };
  74028. // colors shifting and distortion
  74029. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74030. var _this = this;
  74031. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74032. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74033. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74034. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74035. this._depthOfFieldPostProcess.onApply = function (effect) {
  74036. effect.setTexture("depthSampler", _this._depthTexture);
  74037. effect.setTexture("grainSampler", _this._grainTexture);
  74038. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74039. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74040. effect.setFloat('grain_amount', _this._grainAmount);
  74041. effect.setBool('blur_noise', _this._blurNoise);
  74042. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74043. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74044. effect.setFloat('distortion', _this._distortion);
  74045. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74046. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74047. effect.setFloat('aperture', _this._dofAperture);
  74048. effect.setFloat('darken', _this._dofDarken);
  74049. effect.setFloat('edge_blur', _this._edgeBlur);
  74050. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74051. if (_this._scene.activeCamera) {
  74052. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74053. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74054. }
  74055. };
  74056. };
  74057. // creates a black and white random noise texture, 512x512
  74058. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74059. var size = 512;
  74060. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74061. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74062. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74063. var context = this._grainTexture.getContext();
  74064. var rand = function (min, max) {
  74065. return Math.random() * (max - min) + min;
  74066. };
  74067. var value;
  74068. for (var x = 0; x < size; x++) {
  74069. for (var y = 0; y < size; y++) {
  74070. value = Math.floor(rand(0.42, 0.58) * 255);
  74071. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74072. context.fillRect(x, y, 1, 1);
  74073. }
  74074. }
  74075. this._grainTexture.update(false);
  74076. };
  74077. return LensRenderingPipeline;
  74078. }(BABYLON.PostProcessRenderPipeline));
  74079. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74080. })(BABYLON || (BABYLON = {}));
  74081. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74082. var BABYLON;
  74083. (function (BABYLON) {
  74084. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74085. __extends(StandardRenderingPipeline, _super);
  74086. /**
  74087. * @constructor
  74088. * @param {string} name - The rendering pipeline name
  74089. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74090. * @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)
  74091. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74092. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74093. */
  74094. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74095. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74096. var _this = _super.call(this, scene.getEngine(), name) || this;
  74097. _this.downSampleX4PostProcess = null;
  74098. _this.brightPassPostProcess = null;
  74099. _this.blurHPostProcesses = [];
  74100. _this.blurVPostProcesses = [];
  74101. _this.textureAdderPostProcess = null;
  74102. _this.volumetricLightPostProcess = null;
  74103. _this.volumetricLightSmoothXPostProcess = null;
  74104. _this.volumetricLightSmoothYPostProcess = null;
  74105. _this.volumetricLightMergePostProces = null;
  74106. _this.volumetricLightFinalPostProcess = null;
  74107. _this.luminancePostProcess = null;
  74108. _this.luminanceDownSamplePostProcesses = [];
  74109. _this.hdrPostProcess = null;
  74110. _this.textureAdderFinalPostProcess = null;
  74111. _this.lensFlareFinalPostProcess = null;
  74112. _this.hdrFinalPostProcess = null;
  74113. _this.lensFlarePostProcess = null;
  74114. _this.lensFlareComposePostProcess = null;
  74115. _this.motionBlurPostProcess = null;
  74116. _this.depthOfFieldPostProcess = null;
  74117. // Values
  74118. _this.brightThreshold = 1.0;
  74119. _this.blurWidth = 512.0;
  74120. _this.horizontalBlur = false;
  74121. _this.exposure = 1.0;
  74122. _this.lensTexture = null;
  74123. _this.volumetricLightCoefficient = 0.2;
  74124. _this.volumetricLightPower = 4.0;
  74125. _this.volumetricLightBlurScale = 64.0;
  74126. _this.sourceLight = null;
  74127. _this.hdrMinimumLuminance = 1.0;
  74128. _this.hdrDecreaseRate = 0.5;
  74129. _this.hdrIncreaseRate = 0.5;
  74130. _this.lensColorTexture = null;
  74131. _this.lensFlareStrength = 20.0;
  74132. _this.lensFlareGhostDispersal = 1.4;
  74133. _this.lensFlareHaloWidth = 0.7;
  74134. _this.lensFlareDistortionStrength = 16.0;
  74135. _this.lensStarTexture = null;
  74136. _this.lensFlareDirtTexture = null;
  74137. _this.depthOfFieldDistance = 10.0;
  74138. _this.depthOfFieldBlurWidth = 64.0;
  74139. _this.motionStrength = 1.0;
  74140. // IAnimatable
  74141. _this.animations = [];
  74142. _this._currentDepthOfFieldSource = null;
  74143. _this._hdrCurrentLuminance = 1.0;
  74144. // Getters and setters
  74145. _this._bloomEnabled = true;
  74146. _this._depthOfFieldEnabled = false;
  74147. _this._vlsEnabled = false;
  74148. _this._lensFlareEnabled = false;
  74149. _this._hdrEnabled = false;
  74150. _this._motionBlurEnabled = false;
  74151. _this._motionBlurSamples = 64.0;
  74152. _this._volumetricLightStepsCount = 50.0;
  74153. _this._cameras = cameras || [];
  74154. // Initialize
  74155. _this._scene = scene;
  74156. _this._basePostProcess = originalPostProcess;
  74157. _this._ratio = ratio;
  74158. // Misc
  74159. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74160. // Finish
  74161. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74162. _this._buildPipeline();
  74163. return _this;
  74164. }
  74165. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74166. get: function () {
  74167. return this._bloomEnabled;
  74168. },
  74169. set: function (enabled) {
  74170. if (this._bloomEnabled === enabled) {
  74171. return;
  74172. }
  74173. this._bloomEnabled = enabled;
  74174. this._buildPipeline();
  74175. },
  74176. enumerable: true,
  74177. configurable: true
  74178. });
  74179. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74180. get: function () {
  74181. return this._depthOfFieldEnabled;
  74182. },
  74183. set: function (enabled) {
  74184. if (this._depthOfFieldEnabled === enabled) {
  74185. return;
  74186. }
  74187. this._depthOfFieldEnabled = enabled;
  74188. this._buildPipeline();
  74189. },
  74190. enumerable: true,
  74191. configurable: true
  74192. });
  74193. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74194. get: function () {
  74195. return this._lensFlareEnabled;
  74196. },
  74197. set: function (enabled) {
  74198. if (this._lensFlareEnabled === enabled) {
  74199. return;
  74200. }
  74201. this._lensFlareEnabled = enabled;
  74202. this._buildPipeline();
  74203. },
  74204. enumerable: true,
  74205. configurable: true
  74206. });
  74207. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74208. get: function () {
  74209. return this._hdrEnabled;
  74210. },
  74211. set: function (enabled) {
  74212. if (this._hdrEnabled === enabled) {
  74213. return;
  74214. }
  74215. this._hdrEnabled = enabled;
  74216. this._buildPipeline();
  74217. },
  74218. enumerable: true,
  74219. configurable: true
  74220. });
  74221. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74222. get: function () {
  74223. return this._vlsEnabled;
  74224. },
  74225. set: function (enabled) {
  74226. if (this._vlsEnabled === enabled) {
  74227. return;
  74228. }
  74229. if (enabled) {
  74230. var geometry = this._scene.enableGeometryBufferRenderer();
  74231. if (!geometry) {
  74232. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74233. return;
  74234. }
  74235. }
  74236. this._vlsEnabled = enabled;
  74237. this._buildPipeline();
  74238. },
  74239. enumerable: true,
  74240. configurable: true
  74241. });
  74242. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74243. get: function () {
  74244. return this._motionBlurEnabled;
  74245. },
  74246. set: function (enabled) {
  74247. if (this._motionBlurEnabled === enabled) {
  74248. return;
  74249. }
  74250. this._motionBlurEnabled = enabled;
  74251. this._buildPipeline();
  74252. },
  74253. enumerable: true,
  74254. configurable: true
  74255. });
  74256. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74257. get: function () {
  74258. return this._volumetricLightStepsCount;
  74259. },
  74260. set: function (count) {
  74261. if (this.volumetricLightPostProcess) {
  74262. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74263. }
  74264. this._volumetricLightStepsCount = count;
  74265. },
  74266. enumerable: true,
  74267. configurable: true
  74268. });
  74269. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74270. get: function () {
  74271. return this._motionBlurSamples;
  74272. },
  74273. set: function (samples) {
  74274. if (this.motionBlurPostProcess) {
  74275. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74276. }
  74277. this._motionBlurSamples = samples;
  74278. },
  74279. enumerable: true,
  74280. configurable: true
  74281. });
  74282. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74283. var _this = this;
  74284. var ratio = this._ratio;
  74285. var scene = this._scene;
  74286. this._disposePostProcesses();
  74287. this._reset();
  74288. // Create pass post-process
  74289. if (!this._basePostProcess) {
  74290. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74291. this.originalPostProcess.onApply = function (effect) {
  74292. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74293. };
  74294. }
  74295. else {
  74296. this.originalPostProcess = this._basePostProcess;
  74297. }
  74298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74299. this._currentDepthOfFieldSource = this.originalPostProcess;
  74300. if (this._bloomEnabled) {
  74301. // Create down sample X4 post-process
  74302. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74303. // Create bright pass post-process
  74304. this._createBrightPassPostProcess(scene, ratio / 2);
  74305. // Create gaussian blur post-processes (down sampling blurs)
  74306. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74307. // Create texture adder post-process
  74308. this._createTextureAdderPostProcess(scene, ratio);
  74309. // Create depth-of-field source post-process
  74310. 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);
  74311. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74312. }
  74313. if (this._vlsEnabled) {
  74314. // Create volumetric light
  74315. this._createVolumetricLightPostProcess(scene, ratio);
  74316. // Create volumetric light final post-process
  74317. 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);
  74318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74319. }
  74320. if (this._lensFlareEnabled) {
  74321. // Create lens flare post-process
  74322. this._createLensFlarePostProcess(scene, ratio);
  74323. // Create depth-of-field source post-process post lens-flare and disable it now
  74324. 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);
  74325. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74326. }
  74327. if (this._hdrEnabled) {
  74328. // Create luminance
  74329. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74330. // Create HDR
  74331. this._createHdrPostProcess(scene, ratio);
  74332. // Create depth-of-field source post-process post hdr and disable it now
  74333. 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);
  74334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74335. }
  74336. if (this._depthOfFieldEnabled) {
  74337. // Create gaussian blur used by depth-of-field
  74338. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74339. // Create depth-of-field post-process
  74340. this._createDepthOfFieldPostProcess(scene, ratio);
  74341. }
  74342. if (this._motionBlurEnabled) {
  74343. // Create motion blur post-process
  74344. this._createMotionBlurPostProcess(scene, ratio);
  74345. }
  74346. if (this._cameras !== null) {
  74347. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74348. }
  74349. };
  74350. // Down Sample X4 Post-Processs
  74351. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74352. var _this = this;
  74353. var downSampleX4Offsets = new Array(32);
  74354. 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);
  74355. this.downSampleX4PostProcess.onApply = function (effect) {
  74356. var id = 0;
  74357. var width = _this.downSampleX4PostProcess.width;
  74358. var height = _this.downSampleX4PostProcess.height;
  74359. for (var i = -2; i < 2; i++) {
  74360. for (var j = -2; j < 2; j++) {
  74361. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74362. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74363. id += 2;
  74364. }
  74365. }
  74366. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74367. };
  74368. // Add to pipeline
  74369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74370. };
  74371. // Brightpass Post-Process
  74372. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74373. var _this = this;
  74374. var brightOffsets = new Array(8);
  74375. 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);
  74376. this.brightPassPostProcess.onApply = function (effect) {
  74377. var sU = (1.0 / _this.brightPassPostProcess.width);
  74378. var sV = (1.0 / _this.brightPassPostProcess.height);
  74379. brightOffsets[0] = -0.5 * sU;
  74380. brightOffsets[1] = 0.5 * sV;
  74381. brightOffsets[2] = 0.5 * sU;
  74382. brightOffsets[3] = 0.5 * sV;
  74383. brightOffsets[4] = -0.5 * sU;
  74384. brightOffsets[5] = -0.5 * sV;
  74385. brightOffsets[6] = 0.5 * sU;
  74386. brightOffsets[7] = -0.5 * sV;
  74387. effect.setArray2("dsOffsets", brightOffsets);
  74388. effect.setFloat("brightThreshold", _this.brightThreshold);
  74389. };
  74390. // Add to pipeline
  74391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74392. };
  74393. // Create blur H&V post-processes
  74394. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74395. var _this = this;
  74396. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74397. var engine = scene.getEngine();
  74398. 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);
  74399. 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);
  74400. blurX.onActivateObservable.add(function () {
  74401. var dw = blurX.width / engine.getRenderWidth();
  74402. blurX.kernel = _this[blurWidthKey] * dw;
  74403. });
  74404. blurY.onActivateObservable.add(function () {
  74405. var dw = blurY.height / engine.getRenderHeight();
  74406. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74407. });
  74408. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74409. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74410. this.blurHPostProcesses.push(blurX);
  74411. this.blurVPostProcesses.push(blurY);
  74412. };
  74413. // Create texture adder post-process
  74414. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74415. var _this = this;
  74416. 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);
  74417. this.textureAdderPostProcess.onApply = function (effect) {
  74418. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74419. effect.setTexture("lensSampler", _this.lensTexture);
  74420. effect.setFloat("exposure", _this.exposure);
  74421. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74422. };
  74423. // Add to pipeline
  74424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74425. };
  74426. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74427. var _this = this;
  74428. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74429. geometryRenderer.enablePosition = true;
  74430. var geometry = geometryRenderer.getGBuffer();
  74431. // Base post-process
  74432. 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));
  74433. var depthValues = BABYLON.Vector2.Zero();
  74434. this.volumetricLightPostProcess.onApply = function (effect) {
  74435. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74436. var generator = _this.sourceLight.getShadowGenerator();
  74437. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74438. effect.setTexture("positionSampler", geometry.textures[2]);
  74439. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74440. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74441. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74442. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74443. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74444. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74445. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74446. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74447. effect.setVector2("depthValues", depthValues);
  74448. }
  74449. };
  74450. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74451. // Smooth
  74452. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74453. // Merge
  74454. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74455. this.volumetricLightMergePostProces.onApply = function (effect) {
  74456. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74457. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74458. };
  74459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74460. };
  74461. // Create luminance
  74462. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74463. var _this = this;
  74464. // Create luminance
  74465. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74466. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74467. var offsets = [];
  74468. this.luminancePostProcess.onApply = function (effect) {
  74469. var sU = (1.0 / _this.luminancePostProcess.width);
  74470. var sV = (1.0 / _this.luminancePostProcess.height);
  74471. offsets[0] = -0.5 * sU;
  74472. offsets[1] = 0.5 * sV;
  74473. offsets[2] = 0.5 * sU;
  74474. offsets[3] = 0.5 * sV;
  74475. offsets[4] = -0.5 * sU;
  74476. offsets[5] = -0.5 * sV;
  74477. offsets[6] = 0.5 * sU;
  74478. offsets[7] = -0.5 * sV;
  74479. effect.setArray2("lumOffsets", offsets);
  74480. };
  74481. // Add to pipeline
  74482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74483. // Create down sample luminance
  74484. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74485. var size = Math.pow(3, i);
  74486. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74487. if (i === 0) {
  74488. defines += "#define FINAL_DOWN_SAMPLER";
  74489. }
  74490. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74491. this.luminanceDownSamplePostProcesses.push(postProcess);
  74492. }
  74493. // Create callbacks and add effects
  74494. var lastLuminance = this.luminancePostProcess;
  74495. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74496. var downSampleOffsets = new Array(18);
  74497. pp.onApply = function (effect) {
  74498. if (!lastLuminance) {
  74499. return;
  74500. }
  74501. var id = 0;
  74502. for (var x = -1; x < 2; x++) {
  74503. for (var y = -1; y < 2; y++) {
  74504. downSampleOffsets[id] = x / lastLuminance.width;
  74505. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74506. id += 2;
  74507. }
  74508. }
  74509. effect.setArray2("dsOffsets", downSampleOffsets);
  74510. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74511. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74512. lastLuminance = _this.luminancePostProcess;
  74513. }
  74514. else {
  74515. lastLuminance = pp;
  74516. }
  74517. };
  74518. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74519. pp.onAfterRender = function (effect) {
  74520. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74521. 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);
  74522. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74523. };
  74524. }
  74525. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74526. });
  74527. };
  74528. // Create HDR post-process
  74529. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74530. var _this = this;
  74531. 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);
  74532. var outputLiminance = 1;
  74533. var time = 0;
  74534. var lastTime = 0;
  74535. this.hdrPostProcess.onApply = function (effect) {
  74536. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74537. time += scene.getEngine().getDeltaTime();
  74538. if (outputLiminance < 0) {
  74539. outputLiminance = _this._hdrCurrentLuminance;
  74540. }
  74541. else {
  74542. var dt = (lastTime - time) / 1000.0;
  74543. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74544. outputLiminance += _this.hdrDecreaseRate * dt;
  74545. }
  74546. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74547. outputLiminance -= _this.hdrIncreaseRate * dt;
  74548. }
  74549. else {
  74550. outputLiminance = _this._hdrCurrentLuminance;
  74551. }
  74552. }
  74553. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74554. effect.setFloat("averageLuminance", outputLiminance);
  74555. lastTime = time;
  74556. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74557. };
  74558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74559. };
  74560. // Create lens flare post-process
  74561. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74562. var _this = this;
  74563. 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);
  74564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74565. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74566. 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);
  74567. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74568. var resolution = new BABYLON.Vector2(0, 0);
  74569. // Lens flare
  74570. this.lensFlarePostProcess.onApply = function (effect) {
  74571. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74572. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74573. effect.setFloat("strength", _this.lensFlareStrength);
  74574. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74575. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74576. // Shift
  74577. resolution.x = _this.lensFlarePostProcess.width;
  74578. resolution.y = _this.lensFlarePostProcess.height;
  74579. effect.setVector2("resolution", resolution);
  74580. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74581. };
  74582. // Compose
  74583. 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);
  74584. 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);
  74585. this.lensFlareComposePostProcess.onApply = function (effect) {
  74586. if (!_this._scene.activeCamera) {
  74587. return;
  74588. }
  74589. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74590. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74591. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74592. // Lens start rotation matrix
  74593. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74594. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74595. 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));
  74596. camRot *= 4.0;
  74597. 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);
  74598. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74599. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74600. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74601. };
  74602. };
  74603. // Create depth-of-field post-process
  74604. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74605. var _this = this;
  74606. 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);
  74607. this.depthOfFieldPostProcess.onApply = function (effect) {
  74608. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74609. effect.setTexture("depthSampler", _this._getDepthTexture());
  74610. effect.setFloat("distance", _this.depthOfFieldDistance);
  74611. };
  74612. // Add to pipeline
  74613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74614. };
  74615. // Create motion blur post-process
  74616. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74617. var _this = this;
  74618. 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);
  74619. var motionScale = 0;
  74620. var prevViewProjection = BABYLON.Matrix.Identity();
  74621. var invViewProjection = BABYLON.Matrix.Identity();
  74622. var viewProjection = BABYLON.Matrix.Identity();
  74623. var screenSize = BABYLON.Vector2.Zero();
  74624. this.motionBlurPostProcess.onApply = function (effect) {
  74625. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74626. viewProjection.invertToRef(invViewProjection);
  74627. effect.setMatrix("inverseViewProjection", invViewProjection);
  74628. effect.setMatrix("prevViewProjection", prevViewProjection);
  74629. prevViewProjection = viewProjection;
  74630. screenSize.x = _this.motionBlurPostProcess.width;
  74631. screenSize.y = _this.motionBlurPostProcess.height;
  74632. effect.setVector2("screenSize", screenSize);
  74633. motionScale = scene.getEngine().getFps() / 60.0;
  74634. effect.setFloat("motionScale", motionScale);
  74635. effect.setFloat("motionStrength", _this.motionStrength);
  74636. effect.setTexture("depthSampler", _this._getDepthTexture());
  74637. };
  74638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74639. };
  74640. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74641. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74642. var renderer = this._scene.enableGeometryBufferRenderer();
  74643. return renderer.getGBuffer().textures[0];
  74644. }
  74645. return this._scene.enableDepthRenderer().getDepthMap();
  74646. };
  74647. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74648. for (var i = 0; i < this._cameras.length; i++) {
  74649. var camera = this._cameras[i];
  74650. if (this.originalPostProcess) {
  74651. this.originalPostProcess.dispose(camera);
  74652. }
  74653. if (this.downSampleX4PostProcess) {
  74654. this.downSampleX4PostProcess.dispose(camera);
  74655. }
  74656. if (this.brightPassPostProcess) {
  74657. this.brightPassPostProcess.dispose(camera);
  74658. }
  74659. if (this.textureAdderPostProcess) {
  74660. this.textureAdderPostProcess.dispose(camera);
  74661. }
  74662. if (this.textureAdderFinalPostProcess) {
  74663. this.textureAdderFinalPostProcess.dispose(camera);
  74664. }
  74665. if (this.volumetricLightPostProcess) {
  74666. this.volumetricLightPostProcess.dispose(camera);
  74667. }
  74668. if (this.volumetricLightSmoothXPostProcess) {
  74669. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74670. }
  74671. if (this.volumetricLightSmoothYPostProcess) {
  74672. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74673. }
  74674. if (this.volumetricLightMergePostProces) {
  74675. this.volumetricLightMergePostProces.dispose(camera);
  74676. }
  74677. if (this.volumetricLightFinalPostProcess) {
  74678. this.volumetricLightFinalPostProcess.dispose(camera);
  74679. }
  74680. if (this.lensFlarePostProcess) {
  74681. this.lensFlarePostProcess.dispose(camera);
  74682. }
  74683. if (this.lensFlareComposePostProcess) {
  74684. this.lensFlareComposePostProcess.dispose(camera);
  74685. }
  74686. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74687. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74688. }
  74689. if (this.luminancePostProcess) {
  74690. this.luminancePostProcess.dispose(camera);
  74691. }
  74692. if (this.hdrPostProcess) {
  74693. this.hdrPostProcess.dispose(camera);
  74694. }
  74695. if (this.hdrFinalPostProcess) {
  74696. this.hdrFinalPostProcess.dispose(camera);
  74697. }
  74698. if (this.depthOfFieldPostProcess) {
  74699. this.depthOfFieldPostProcess.dispose(camera);
  74700. }
  74701. if (this.motionBlurPostProcess) {
  74702. this.motionBlurPostProcess.dispose(camera);
  74703. }
  74704. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74705. this.blurHPostProcesses[j].dispose(camera);
  74706. }
  74707. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74708. this.blurVPostProcesses[j].dispose(camera);
  74709. }
  74710. }
  74711. this.originalPostProcess = null;
  74712. this.downSampleX4PostProcess = null;
  74713. this.brightPassPostProcess = null;
  74714. this.textureAdderPostProcess = null;
  74715. this.textureAdderFinalPostProcess = null;
  74716. this.volumetricLightPostProcess = null;
  74717. this.volumetricLightSmoothXPostProcess = null;
  74718. this.volumetricLightSmoothYPostProcess = null;
  74719. this.volumetricLightMergePostProces = null;
  74720. this.volumetricLightFinalPostProcess = null;
  74721. this.lensFlarePostProcess = null;
  74722. this.lensFlareComposePostProcess = null;
  74723. this.luminancePostProcess = null;
  74724. this.hdrPostProcess = null;
  74725. this.hdrFinalPostProcess = null;
  74726. this.depthOfFieldPostProcess = null;
  74727. this.motionBlurPostProcess = null;
  74728. this.luminanceDownSamplePostProcesses = [];
  74729. this.blurHPostProcesses = [];
  74730. this.blurVPostProcesses = [];
  74731. };
  74732. /**
  74733. * Dispose of the pipeline and stop all post processes
  74734. */
  74735. StandardRenderingPipeline.prototype.dispose = function () {
  74736. this._disposePostProcesses();
  74737. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74738. _super.prototype.dispose.call(this);
  74739. };
  74740. /**
  74741. * Serialize the rendering pipeline (Used when exporting)
  74742. * @returns the serialized object
  74743. */
  74744. StandardRenderingPipeline.prototype.serialize = function () {
  74745. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74746. if (this.sourceLight) {
  74747. serializationObject.sourceLightId = this.sourceLight.id;
  74748. }
  74749. serializationObject.customType = "StandardRenderingPipeline";
  74750. return serializationObject;
  74751. };
  74752. /**
  74753. * Parse the serialized pipeline
  74754. * @param source Source pipeline.
  74755. * @param scene The scene to load the pipeline to.
  74756. * @param rootUrl The URL of the serialized pipeline.
  74757. * @returns An instantiated pipeline from the serialized object.
  74758. */
  74759. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74760. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74761. if (source.sourceLightId) {
  74762. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74763. }
  74764. return p;
  74765. };
  74766. // Luminance steps
  74767. StandardRenderingPipeline.LuminanceSteps = 6;
  74768. __decorate([
  74769. BABYLON.serialize()
  74770. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74771. __decorate([
  74772. BABYLON.serialize()
  74773. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74774. __decorate([
  74775. BABYLON.serialize()
  74776. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74777. __decorate([
  74778. BABYLON.serialize()
  74779. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74780. __decorate([
  74781. BABYLON.serializeAsTexture("lensTexture")
  74782. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74783. __decorate([
  74784. BABYLON.serialize()
  74785. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74786. __decorate([
  74787. BABYLON.serialize()
  74788. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74789. __decorate([
  74790. BABYLON.serialize()
  74791. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74792. __decorate([
  74793. BABYLON.serialize()
  74794. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74795. __decorate([
  74796. BABYLON.serialize()
  74797. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74798. __decorate([
  74799. BABYLON.serialize()
  74800. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74801. __decorate([
  74802. BABYLON.serializeAsTexture("lensColorTexture")
  74803. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74804. __decorate([
  74805. BABYLON.serialize()
  74806. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74807. __decorate([
  74808. BABYLON.serialize()
  74809. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74810. __decorate([
  74811. BABYLON.serialize()
  74812. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74813. __decorate([
  74814. BABYLON.serialize()
  74815. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74816. __decorate([
  74817. BABYLON.serializeAsTexture("lensStarTexture")
  74818. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74819. __decorate([
  74820. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74821. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74822. __decorate([
  74823. BABYLON.serialize()
  74824. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74825. __decorate([
  74826. BABYLON.serialize()
  74827. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74828. __decorate([
  74829. BABYLON.serialize()
  74830. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74831. __decorate([
  74832. BABYLON.serialize()
  74833. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74834. __decorate([
  74835. BABYLON.serialize()
  74836. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74837. __decorate([
  74838. BABYLON.serialize()
  74839. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74840. __decorate([
  74841. BABYLON.serialize()
  74842. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74843. __decorate([
  74844. BABYLON.serialize()
  74845. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74846. __decorate([
  74847. BABYLON.serialize()
  74848. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74849. __decorate([
  74850. BABYLON.serialize()
  74851. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74852. __decorate([
  74853. BABYLON.serialize()
  74854. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74855. __decorate([
  74856. BABYLON.serialize()
  74857. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74858. return StandardRenderingPipeline;
  74859. }(BABYLON.PostProcessRenderPipeline));
  74860. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74861. })(BABYLON || (BABYLON = {}));
  74862. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74863. var BABYLON;
  74864. (function (BABYLON) {
  74865. var FxaaPostProcess = /** @class */ (function (_super) {
  74866. __extends(FxaaPostProcess, _super);
  74867. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74868. if (camera === void 0) { camera = null; }
  74869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74870. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74871. var defines = _this._getDefines();
  74872. _this.updateEffect(defines);
  74873. _this.onApplyObservable.add(function (effect) {
  74874. var texelSize = _this.texelSize;
  74875. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74876. });
  74877. return _this;
  74878. }
  74879. FxaaPostProcess.prototype._getDefines = function () {
  74880. var engine = this.getEngine();
  74881. if (!engine) {
  74882. return null;
  74883. }
  74884. var glInfo = engine.getGlInfo();
  74885. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74886. return "#define MALI 1\n";
  74887. }
  74888. return null;
  74889. };
  74890. return FxaaPostProcess;
  74891. }(BABYLON.PostProcess));
  74892. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74893. })(BABYLON || (BABYLON = {}));
  74894. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74895. var BABYLON;
  74896. (function (BABYLON) {
  74897. /**
  74898. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74899. */
  74900. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74901. __extends(ChromaticAberrationPostProcess, _super);
  74902. /**
  74903. * Creates a new instance ChromaticAberrationPostProcess
  74904. * @param name The name of the effect.
  74905. * @param screenWidth The width of the screen to apply the effect on.
  74906. * @param screenHeight The height of the screen to apply the effect on.
  74907. * @param options The required width/height ratio to downsize to before computing the render pass.
  74908. * @param camera The camera to apply the render pass to.
  74909. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74910. * @param engine The engine which the post process will be applied. (default: current engine)
  74911. * @param reusable If the post process can be reused on the same frame. (default: false)
  74912. * @param textureType Type of textures used when performing the post process. (default: 0)
  74913. * @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)
  74914. */
  74915. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74917. if (blockCompilation === void 0) { blockCompilation = false; }
  74918. 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;
  74919. /**
  74920. * The amount of seperation of rgb channels (default: 30)
  74921. */
  74922. _this.aberrationAmount = 30;
  74923. /**
  74924. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74925. */
  74926. _this.radialIntensity = 0;
  74927. /**
  74928. * 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))
  74929. */
  74930. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74931. /**
  74932. * 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))
  74933. */
  74934. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74935. _this.onApplyObservable.add(function (effect) {
  74936. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74937. effect.setFloat('screen_width', screenWidth);
  74938. effect.setFloat('screen_height', screenHeight);
  74939. effect.setFloat('radialIntensity', _this.radialIntensity);
  74940. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74941. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74942. });
  74943. return _this;
  74944. }
  74945. return ChromaticAberrationPostProcess;
  74946. }(BABYLON.PostProcess));
  74947. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74948. })(BABYLON || (BABYLON = {}));
  74949. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74950. var BABYLON;
  74951. (function (BABYLON) {
  74952. /**
  74953. * The GrainPostProcess adds noise to the image at mid luminance levels
  74954. */
  74955. var GrainPostProcess = /** @class */ (function (_super) {
  74956. __extends(GrainPostProcess, _super);
  74957. /**
  74958. * Creates a new instance of @see GrainPostProcess
  74959. * @param name The name of the effect.
  74960. * @param options The required width/height ratio to downsize to before computing the render pass.
  74961. * @param camera The camera to apply the render pass to.
  74962. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74963. * @param engine The engine which the post process will be applied. (default: current engine)
  74964. * @param reusable If the post process can be reused on the same frame. (default: false)
  74965. * @param textureType Type of textures used when performing the post process. (default: 0)
  74966. * @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)
  74967. */
  74968. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74969. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74970. if (blockCompilation === void 0) { blockCompilation = false; }
  74971. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74972. /**
  74973. * The intensity of the grain added (default: 30)
  74974. */
  74975. _this.intensity = 30;
  74976. /**
  74977. * If the grain should be randomized on every frame
  74978. */
  74979. _this.animated = false;
  74980. _this.onApplyObservable.add(function (effect) {
  74981. effect.setFloat('intensity', _this.intensity);
  74982. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74983. });
  74984. return _this;
  74985. }
  74986. return GrainPostProcess;
  74987. }(BABYLON.PostProcess));
  74988. BABYLON.GrainPostProcess = GrainPostProcess;
  74989. })(BABYLON || (BABYLON = {}));
  74990. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74991. var BABYLON;
  74992. (function (BABYLON) {
  74993. /**
  74994. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74995. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74996. */
  74997. var SharpenPostProcess = /** @class */ (function (_super) {
  74998. __extends(SharpenPostProcess, _super);
  74999. /**
  75000. * Creates a new instance ConvolutionPostProcess
  75001. * @param name The name of the effect.
  75002. * @param options The required width/height ratio to downsize to before computing the render pass.
  75003. * @param camera The camera to apply the render pass to.
  75004. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75005. * @param engine The engine which the post process will be applied. (default: current engine)
  75006. * @param reusable If the post process can be reused on the same frame. (default: false)
  75007. * @param textureType Type of textures used when performing the post process. (default: 0)
  75008. * @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)
  75009. */
  75010. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75011. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75012. if (blockCompilation === void 0) { blockCompilation = false; }
  75013. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75014. /**
  75015. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75016. */
  75017. _this.colorAmount = 1.0;
  75018. /**
  75019. * How much sharpness should be applied (default: 0.3)
  75020. */
  75021. _this.edgeAmount = 0.3;
  75022. _this.onApply = function (effect) {
  75023. effect.setFloat2("screenSize", _this.width, _this.height);
  75024. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75025. };
  75026. return _this;
  75027. }
  75028. return SharpenPostProcess;
  75029. }(BABYLON.PostProcess));
  75030. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75031. })(BABYLON || (BABYLON = {}));
  75032. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75033. var BABYLON;
  75034. (function (BABYLON) {
  75035. /**
  75036. * The Blur Post Process which blurs an image based on a kernel and direction.
  75037. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75038. */
  75039. var BlurPostProcess = /** @class */ (function (_super) {
  75040. __extends(BlurPostProcess, _super);
  75041. /**
  75042. * Creates a new instance BlurPostProcess
  75043. * @param name The name of the effect.
  75044. * @param direction The direction in which to blur the image.
  75045. * @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.
  75046. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75047. * @param camera The camera to apply the render pass to.
  75048. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75049. * @param engine The engine which the post process will be applied. (default: current engine)
  75050. * @param reusable If the post process can be reused on the same frame. (default: false)
  75051. * @param textureType Type of textures used when performing the post process. (default: 0)
  75052. * @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)
  75053. */
  75054. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75056. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75057. if (defines === void 0) { defines = ""; }
  75058. if (blockCompilation === void 0) { blockCompilation = false; }
  75059. 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;
  75060. _this.direction = direction;
  75061. _this.blockCompilation = blockCompilation;
  75062. _this._packedFloat = false;
  75063. _this._staticDefines = "";
  75064. _this._staticDefines = defines;
  75065. _this.onApplyObservable.add(function (effect) {
  75066. if (_this._outputTexture) {
  75067. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75068. }
  75069. else {
  75070. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75071. }
  75072. });
  75073. _this.kernel = kernel;
  75074. return _this;
  75075. }
  75076. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75077. /**
  75078. * Gets the length in pixels of the blur sample region
  75079. */
  75080. get: function () {
  75081. return this._idealKernel;
  75082. },
  75083. /**
  75084. * Sets the length in pixels of the blur sample region
  75085. */
  75086. set: function (v) {
  75087. if (this._idealKernel === v) {
  75088. return;
  75089. }
  75090. v = Math.max(v, 1);
  75091. this._idealKernel = v;
  75092. this._kernel = this._nearestBestKernel(v);
  75093. if (!this.blockCompilation) {
  75094. this._updateParameters();
  75095. }
  75096. },
  75097. enumerable: true,
  75098. configurable: true
  75099. });
  75100. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75101. /**
  75102. * Gets wether or not the blur is unpacking/repacking floats
  75103. */
  75104. get: function () {
  75105. return this._packedFloat;
  75106. },
  75107. /**
  75108. * Sets wether or not the blur needs to unpack/repack floats
  75109. */
  75110. set: function (v) {
  75111. if (this._packedFloat === v) {
  75112. return;
  75113. }
  75114. this._packedFloat = v;
  75115. if (!this.blockCompilation) {
  75116. this._updateParameters();
  75117. }
  75118. },
  75119. enumerable: true,
  75120. configurable: true
  75121. });
  75122. /**
  75123. * Updates the effect with the current post process compile time values and recompiles the shader.
  75124. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75125. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75126. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75127. * @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
  75128. * @param onCompiled Called when the shader has been compiled.
  75129. * @param onError Called if there is an error when compiling a shader.
  75130. */
  75131. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75132. if (defines === void 0) { defines = null; }
  75133. if (uniforms === void 0) { uniforms = null; }
  75134. if (samplers === void 0) { samplers = null; }
  75135. this._updateParameters(onCompiled, onError);
  75136. };
  75137. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75138. // Generate sampling offsets and weights
  75139. var N = this._kernel;
  75140. var centerIndex = (N - 1) / 2;
  75141. // Generate Gaussian sampling weights over kernel
  75142. var offsets = [];
  75143. var weights = [];
  75144. var totalWeight = 0;
  75145. for (var i = 0; i < N; i++) {
  75146. var u = i / (N - 1);
  75147. var w = this._gaussianWeight(u * 2.0 - 1);
  75148. offsets[i] = (i - centerIndex);
  75149. weights[i] = w;
  75150. totalWeight += w;
  75151. }
  75152. // Normalize weights
  75153. for (var i = 0; i < weights.length; i++) {
  75154. weights[i] /= totalWeight;
  75155. }
  75156. // Optimize: combine samples to take advantage of hardware linear sampling
  75157. // Walk from left to center, combining pairs (symmetrically)
  75158. var linearSamplingWeights = [];
  75159. var linearSamplingOffsets = [];
  75160. var linearSamplingMap = [];
  75161. for (var i = 0; i <= centerIndex; i += 2) {
  75162. var j = Math.min(i + 1, Math.floor(centerIndex));
  75163. var singleCenterSample = i === j;
  75164. if (singleCenterSample) {
  75165. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75166. }
  75167. else {
  75168. var sharedCell = j === centerIndex;
  75169. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75170. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75171. if (offsetLinear === 0) {
  75172. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75173. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75174. }
  75175. else {
  75176. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75177. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75178. }
  75179. }
  75180. }
  75181. for (var i = 0; i < linearSamplingMap.length; i++) {
  75182. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75183. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75184. }
  75185. // Replace with optimized
  75186. offsets = linearSamplingOffsets;
  75187. weights = linearSamplingWeights;
  75188. // Generate shaders
  75189. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75190. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75191. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75192. var defines = "";
  75193. defines += this._staticDefines;
  75194. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75195. if (this._staticDefines.indexOf("DOF") != -1) {
  75196. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75197. varyingCount--;
  75198. }
  75199. for (var i = 0; i < varyingCount; i++) {
  75200. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75201. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75202. }
  75203. var depCount = 0;
  75204. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75205. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75206. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75207. depCount++;
  75208. }
  75209. if (this.packedFloat) {
  75210. defines += "#define PACKEDFLOAT 1";
  75211. }
  75212. this.blockCompilation = false;
  75213. _super.prototype.updateEffect.call(this, defines, null, null, {
  75214. varyingCount: varyingCount,
  75215. depCount: depCount
  75216. }, onCompiled, onError);
  75217. };
  75218. /**
  75219. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75220. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75221. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75222. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75223. * The gaps between physical kernels are compensated for in the weighting of the samples
  75224. * @param idealKernel Ideal blur kernel.
  75225. * @return Nearest best kernel.
  75226. */
  75227. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75228. var v = Math.round(idealKernel);
  75229. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75230. var k = _a[_i];
  75231. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75232. return Math.max(k, 3);
  75233. }
  75234. }
  75235. return Math.max(v, 3);
  75236. };
  75237. /**
  75238. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75239. * @param x The point on the Gaussian distribution to sample.
  75240. * @return the value of the Gaussian function at x.
  75241. */
  75242. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75243. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75244. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75245. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75246. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75247. // truncated at around 1.3% of peak strength.
  75248. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75249. var sigma = (1 / 3);
  75250. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75251. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75252. var weight = (1.0 / denominator) * Math.exp(exponent);
  75253. return weight;
  75254. };
  75255. /**
  75256. * Generates a string that can be used as a floating point number in GLSL.
  75257. * @param x Value to print.
  75258. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75259. * @return GLSL float string.
  75260. */
  75261. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75262. if (decimalFigures === void 0) { decimalFigures = 8; }
  75263. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75264. };
  75265. return BlurPostProcess;
  75266. }(BABYLON.PostProcess));
  75267. BABYLON.BlurPostProcess = BlurPostProcess;
  75268. })(BABYLON || (BABYLON = {}));
  75269. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75270. var BABYLON;
  75271. (function (BABYLON) {
  75272. /**
  75273. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75274. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75275. * based on samples that have a large difference in distance than the center pixel.
  75276. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75277. */
  75278. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75279. __extends(DepthOfFieldBlurPostProcess, _super);
  75280. /**
  75281. * Creates a new instance CircleOfConfusionPostProcess
  75282. * @param name The name of the effect.
  75283. * @param scene The scene the effect belongs to.
  75284. * @param direction The direction the blur should be applied.
  75285. * @param kernel The size of the kernel used to blur.
  75286. * @param options The required width/height ratio to downsize to before computing the render pass.
  75287. * @param camera The camera to apply the render pass to.
  75288. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75289. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75290. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75291. * @param engine The engine which the post process will be applied. (default: current engine)
  75292. * @param reusable If the post process can be reused on the same frame. (default: false)
  75293. * @param textureType Type of textures used when performing the post process. (default: 0)
  75294. * @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)
  75295. */
  75296. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75297. if (imageToBlur === void 0) { imageToBlur = null; }
  75298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75299. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75300. if (blockCompilation === void 0) { blockCompilation = false; }
  75301. 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;
  75302. _this.direction = direction;
  75303. _this.onApplyObservable.add(function (effect) {
  75304. if (imageToBlur != null) {
  75305. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75306. }
  75307. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75308. if (scene.activeCamera) {
  75309. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75310. }
  75311. });
  75312. return _this;
  75313. }
  75314. return DepthOfFieldBlurPostProcess;
  75315. }(BABYLON.BlurPostProcess));
  75316. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75317. })(BABYLON || (BABYLON = {}));
  75318. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75319. var BABYLON;
  75320. (function (BABYLON) {
  75321. /**
  75322. * Options to be set when merging outputs from the default pipeline.
  75323. */
  75324. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75325. function DepthOfFieldMergePostProcessOptions() {
  75326. }
  75327. return DepthOfFieldMergePostProcessOptions;
  75328. }());
  75329. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75330. /**
  75331. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75332. */
  75333. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75334. __extends(DepthOfFieldMergePostProcess, _super);
  75335. /**
  75336. * Creates a new instance of DepthOfFieldMergePostProcess
  75337. * @param name The name of the effect.
  75338. * @param originalFromInput Post process which's input will be used for the merge.
  75339. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75340. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75341. * @param options The required width/height ratio to downsize to before computing the render pass.
  75342. * @param camera The camera to apply the render pass to.
  75343. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75344. * @param engine The engine which the post process will be applied. (default: current engine)
  75345. * @param reusable If the post process can be reused on the same frame. (default: false)
  75346. * @param textureType Type of textures used when performing the post process. (default: 0)
  75347. * @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)
  75348. */
  75349. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75350. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75351. if (blockCompilation === void 0) { blockCompilation = false; }
  75352. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75353. _this.blurSteps = blurSteps;
  75354. _this.onApplyObservable.add(function (effect) {
  75355. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75356. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75357. blurSteps.forEach(function (step, index) {
  75358. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75359. });
  75360. });
  75361. if (!blockCompilation) {
  75362. _this.updateEffect();
  75363. }
  75364. return _this;
  75365. }
  75366. /**
  75367. * Updates the effect with the current post process compile time values and recompiles the shader.
  75368. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75369. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75370. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75371. * @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
  75372. * @param onCompiled Called when the shader has been compiled.
  75373. * @param onError Called if there is an error when compiling a shader.
  75374. */
  75375. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75376. if (defines === void 0) { defines = null; }
  75377. if (uniforms === void 0) { uniforms = null; }
  75378. if (samplers === void 0) { samplers = null; }
  75379. if (!defines) {
  75380. defines = "";
  75381. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75382. }
  75383. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75384. };
  75385. return DepthOfFieldMergePostProcess;
  75386. }(BABYLON.PostProcess));
  75387. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75388. })(BABYLON || (BABYLON = {}));
  75389. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75390. var BABYLON;
  75391. (function (BABYLON) {
  75392. /**
  75393. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75394. */
  75395. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75396. __extends(CircleOfConfusionPostProcess, _super);
  75397. /**
  75398. * Creates a new instance CircleOfConfusionPostProcess
  75399. * @param name The name of the effect.
  75400. * @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.
  75401. * @param options The required width/height ratio to downsize to before computing the render pass.
  75402. * @param camera The camera to apply the render pass to.
  75403. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75404. * @param engine The engine which the post process will be applied. (default: current engine)
  75405. * @param reusable If the post process can be reused on the same frame. (default: false)
  75406. * @param textureType Type of textures used when performing the post process. (default: 0)
  75407. * @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)
  75408. */
  75409. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75411. if (blockCompilation === void 0) { blockCompilation = false; }
  75412. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75413. /**
  75414. * 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.
  75415. */
  75416. _this.lensSize = 50;
  75417. /**
  75418. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75419. */
  75420. _this.fStop = 1.4;
  75421. /**
  75422. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75423. */
  75424. _this.focusDistance = 2000;
  75425. /**
  75426. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75427. */
  75428. _this.focalLength = 50;
  75429. _this._depthTexture = null;
  75430. _this._depthTexture = depthTexture;
  75431. _this.onApplyObservable.add(function (effect) {
  75432. if (!_this._depthTexture) {
  75433. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75434. return;
  75435. }
  75436. effect.setTexture("depthSampler", _this._depthTexture);
  75437. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75438. var aperture = _this.lensSize / _this.fStop;
  75439. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75440. effect.setFloat('focusDistance', _this.focusDistance);
  75441. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75442. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75443. });
  75444. return _this;
  75445. }
  75446. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75447. /**
  75448. * 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.
  75449. */
  75450. set: function (value) {
  75451. this._depthTexture = value;
  75452. },
  75453. enumerable: true,
  75454. configurable: true
  75455. });
  75456. return CircleOfConfusionPostProcess;
  75457. }(BABYLON.PostProcess));
  75458. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75459. })(BABYLON || (BABYLON = {}));
  75460. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75461. var BABYLON;
  75462. (function (BABYLON) {
  75463. /**
  75464. * Specifies the level of max blur that should be applied when using the depth of field effect
  75465. */
  75466. var DepthOfFieldEffectBlurLevel;
  75467. (function (DepthOfFieldEffectBlurLevel) {
  75468. /**
  75469. * Subtle blur
  75470. */
  75471. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75472. /**
  75473. * Medium blur
  75474. */
  75475. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75476. /**
  75477. * Large blur
  75478. */
  75479. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75480. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75481. ;
  75482. /**
  75483. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75484. */
  75485. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75486. __extends(DepthOfFieldEffect, _super);
  75487. /**
  75488. * Creates a new instance DepthOfFieldEffect
  75489. * @param scene The scene the effect belongs to.
  75490. * @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.
  75491. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75492. * @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)
  75493. */
  75494. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75495. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75496. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75497. if (blockCompilation === void 0) { blockCompilation = false; }
  75498. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75499. return _this._effects;
  75500. }, true) || this;
  75501. /**
  75502. * Internal post processes in depth of field effect
  75503. */
  75504. _this._effects = [];
  75505. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75506. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75507. // 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)
  75508. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75509. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75510. _this._depthOfFieldBlurY = [];
  75511. _this._depthOfFieldBlurX = [];
  75512. var blurCount = 1;
  75513. var kernelSize = 15;
  75514. switch (blurLevel) {
  75515. case DepthOfFieldEffectBlurLevel.High: {
  75516. blurCount = 3;
  75517. kernelSize = 51;
  75518. break;
  75519. }
  75520. case DepthOfFieldEffectBlurLevel.Medium: {
  75521. blurCount = 2;
  75522. kernelSize = 31;
  75523. break;
  75524. }
  75525. default: {
  75526. kernelSize = 15;
  75527. blurCount = 1;
  75528. break;
  75529. }
  75530. }
  75531. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75532. var ratio = 1.0;
  75533. for (var i = 0; i < blurCount; i++) {
  75534. 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);
  75535. blurY.autoClear = false;
  75536. ratio = 0.75 / Math.pow(2, i);
  75537. 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);
  75538. blurX.autoClear = false;
  75539. _this._depthOfFieldBlurY.push(blurY);
  75540. _this._depthOfFieldBlurX.push(blurX);
  75541. }
  75542. // Set all post processes on the effect.
  75543. _this._effects = [_this._circleOfConfusion];
  75544. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75545. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75546. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75547. }
  75548. // Merge blurred images with original image based on circleOfConfusion
  75549. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75550. _this._dofMerge.autoClear = false;
  75551. _this._effects.push(_this._dofMerge);
  75552. return _this;
  75553. }
  75554. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75555. get: function () {
  75556. return this._circleOfConfusion.focalLength;
  75557. },
  75558. /**
  75559. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75560. */
  75561. set: function (value) {
  75562. this._circleOfConfusion.focalLength = value;
  75563. },
  75564. enumerable: true,
  75565. configurable: true
  75566. });
  75567. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75568. get: function () {
  75569. return this._circleOfConfusion.fStop;
  75570. },
  75571. /**
  75572. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75573. */
  75574. set: function (value) {
  75575. this._circleOfConfusion.fStop = value;
  75576. },
  75577. enumerable: true,
  75578. configurable: true
  75579. });
  75580. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75581. get: function () {
  75582. return this._circleOfConfusion.focusDistance;
  75583. },
  75584. /**
  75585. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75586. */
  75587. set: function (value) {
  75588. this._circleOfConfusion.focusDistance = value;
  75589. },
  75590. enumerable: true,
  75591. configurable: true
  75592. });
  75593. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75594. get: function () {
  75595. return this._circleOfConfusion.lensSize;
  75596. },
  75597. /**
  75598. * 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.
  75599. */
  75600. set: function (value) {
  75601. this._circleOfConfusion.lensSize = value;
  75602. },
  75603. enumerable: true,
  75604. configurable: true
  75605. });
  75606. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75607. /**
  75608. * 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.
  75609. */
  75610. set: function (value) {
  75611. this._circleOfConfusion.depthTexture = value;
  75612. },
  75613. enumerable: true,
  75614. configurable: true
  75615. });
  75616. /**
  75617. * Disposes each of the internal effects for a given camera.
  75618. * @param camera The camera to dispose the effect on.
  75619. */
  75620. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75621. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75622. this._effects[effectIndex].dispose(camera);
  75623. }
  75624. };
  75625. /**
  75626. * Internal
  75627. */
  75628. DepthOfFieldEffect.prototype._updateEffects = function () {
  75629. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75630. this._effects[effectIndex].updateEffect();
  75631. }
  75632. };
  75633. /**
  75634. * Internal
  75635. * @returns if all the contained post processes are ready.
  75636. */
  75637. DepthOfFieldEffect.prototype._isReady = function () {
  75638. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75639. if (!this._effects[effectIndex].isReady()) {
  75640. return false;
  75641. }
  75642. }
  75643. return true;
  75644. };
  75645. return DepthOfFieldEffect;
  75646. }(BABYLON.PostProcessRenderEffect));
  75647. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75648. })(BABYLON || (BABYLON = {}));
  75649. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75650. var BABYLON;
  75651. (function (BABYLON) {
  75652. /**
  75653. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75654. */
  75655. var BloomMergePostProcess = /** @class */ (function (_super) {
  75656. __extends(BloomMergePostProcess, _super);
  75657. /**
  75658. * Creates a new instance of @see BloomMergePostProcess
  75659. * @param name The name of the effect.
  75660. * @param originalFromInput Post process which's input will be used for the merge.
  75661. * @param blurred Blurred highlights post process which's output will be used.
  75662. * @param weight Weight of the bloom to be added to the original input.
  75663. * @param options The required width/height ratio to downsize to before computing the render pass.
  75664. * @param camera The camera to apply the render pass to.
  75665. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75666. * @param engine The engine which the post process will be applied. (default: current engine)
  75667. * @param reusable If the post process can be reused on the same frame. (default: false)
  75668. * @param textureType Type of textures used when performing the post process. (default: 0)
  75669. * @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)
  75670. */
  75671. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75672. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75673. if (blockCompilation === void 0) { blockCompilation = false; }
  75674. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75675. _this.weight = weight;
  75676. _this.onApplyObservable.add(function (effect) {
  75677. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75678. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75679. effect.setFloat("bloomWeight", _this.weight);
  75680. });
  75681. if (!blockCompilation) {
  75682. _this.updateEffect();
  75683. }
  75684. return _this;
  75685. }
  75686. return BloomMergePostProcess;
  75687. }(BABYLON.PostProcess));
  75688. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75689. })(BABYLON || (BABYLON = {}));
  75690. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75691. var BABYLON;
  75692. (function (BABYLON) {
  75693. /**
  75694. * 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.
  75695. */
  75696. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75697. __extends(ExtractHighlightsPostProcess, _super);
  75698. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75700. if (blockCompilation === void 0) { blockCompilation = false; }
  75701. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75702. /**
  75703. * The luminance threshold, pixels below this value will be set to black.
  75704. */
  75705. _this.threshold = 0.9;
  75706. /**
  75707. * Internal
  75708. */
  75709. _this._exposure = 1;
  75710. /**
  75711. * Post process which has the input texture to be used when performing highlight extraction
  75712. */
  75713. _this._inputPostProcess = null;
  75714. _this.onApplyObservable.add(function (effect) {
  75715. if (_this._inputPostProcess) {
  75716. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75717. }
  75718. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75719. effect.setFloat('exposure', _this._exposure);
  75720. });
  75721. return _this;
  75722. }
  75723. return ExtractHighlightsPostProcess;
  75724. }(BABYLON.PostProcess));
  75725. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75726. })(BABYLON || (BABYLON = {}));
  75727. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75728. var BABYLON;
  75729. (function (BABYLON) {
  75730. /**
  75731. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75732. */
  75733. var BloomEffect = /** @class */ (function (_super) {
  75734. __extends(BloomEffect, _super);
  75735. /**
  75736. * Creates a new instance of @see BloomEffect
  75737. * @param scene The scene the effect belongs to.
  75738. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75739. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75740. * @param bloomWeight The the strength of bloom.
  75741. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75742. * @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)
  75743. */
  75744. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75745. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75746. if (blockCompilation === void 0) { blockCompilation = false; }
  75747. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75748. return _this._effects;
  75749. }, true) || this;
  75750. _this.bloomScale = bloomScale;
  75751. /**
  75752. * Internal
  75753. */
  75754. _this._effects = [];
  75755. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75756. _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);
  75757. _this._blurX.alwaysForcePOT = true;
  75758. _this._blurX.autoClear = false;
  75759. _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);
  75760. _this._blurY.alwaysForcePOT = true;
  75761. _this._blurY.autoClear = false;
  75762. _this.kernel = bloomKernel;
  75763. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75764. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75765. _this._merge.autoClear = false;
  75766. _this._effects.push(_this._merge);
  75767. return _this;
  75768. }
  75769. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75770. /**
  75771. * The luminance threshold to find bright areas of the image to bloom.
  75772. */
  75773. get: function () {
  75774. return this._downscale.threshold;
  75775. },
  75776. set: function (value) {
  75777. this._downscale.threshold = value;
  75778. },
  75779. enumerable: true,
  75780. configurable: true
  75781. });
  75782. Object.defineProperty(BloomEffect.prototype, "weight", {
  75783. /**
  75784. * The strength of the bloom.
  75785. */
  75786. get: function () {
  75787. return this._merge.weight;
  75788. },
  75789. set: function (value) {
  75790. this._merge.weight = value;
  75791. },
  75792. enumerable: true,
  75793. configurable: true
  75794. });
  75795. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75796. /**
  75797. * Specifies the size of the bloom blur kernel, relative to the final output size
  75798. */
  75799. get: function () {
  75800. return this._blurX.kernel / this.bloomScale;
  75801. },
  75802. set: function (value) {
  75803. this._blurX.kernel = value * this.bloomScale;
  75804. this._blurY.kernel = value * this.bloomScale;
  75805. },
  75806. enumerable: true,
  75807. configurable: true
  75808. });
  75809. /**
  75810. * Disposes each of the internal effects for a given camera.
  75811. * @param camera The camera to dispose the effect on.
  75812. */
  75813. BloomEffect.prototype.disposeEffects = function (camera) {
  75814. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75815. this._effects[effectIndex].dispose(camera);
  75816. }
  75817. };
  75818. /**
  75819. * Internal
  75820. */
  75821. BloomEffect.prototype._updateEffects = function () {
  75822. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75823. this._effects[effectIndex].updateEffect();
  75824. }
  75825. };
  75826. /**
  75827. * Internal
  75828. * @returns if all the contained post processes are ready.
  75829. */
  75830. BloomEffect.prototype._isReady = function () {
  75831. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75832. if (!this._effects[effectIndex].isReady()) {
  75833. return false;
  75834. }
  75835. }
  75836. return true;
  75837. };
  75838. return BloomEffect;
  75839. }(BABYLON.PostProcessRenderEffect));
  75840. BABYLON.BloomEffect = BloomEffect;
  75841. })(BABYLON || (BABYLON = {}));
  75842. //# sourceMappingURL=babylon.bloomEffect.js.map
  75843. var BABYLON;
  75844. (function (BABYLON) {
  75845. /**
  75846. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75847. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75848. */
  75849. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75850. __extends(DefaultRenderingPipeline, _super);
  75851. /**
  75852. * @constructor
  75853. * @param {string} name - The rendering pipeline name (default: "")
  75854. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75855. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75856. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75857. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75858. */
  75859. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75860. if (name === void 0) { name = ""; }
  75861. if (hdr === void 0) { hdr = true; }
  75862. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75863. if (automaticBuild === void 0) { automaticBuild = true; }
  75864. var _this = _super.call(this, scene.getEngine(), name) || this;
  75865. _this._originalCameras = [];
  75866. /**
  75867. * ID of the sharpen post process,
  75868. */
  75869. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75870. /**
  75871. * ID of the image processing post process;
  75872. */
  75873. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75874. /**
  75875. * ID of the Fast Approximate Anti-Aliasing post process;
  75876. */
  75877. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75878. /**
  75879. * ID of the chromatic aberration post process,
  75880. */
  75881. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75882. /**
  75883. * ID of the grain post process
  75884. */
  75885. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75886. /**
  75887. * Glow post process which adds a glow to emmisive areas of the image
  75888. */
  75889. _this._glowLayer = null;
  75890. /**
  75891. * Animations which can be used to tweak settings over a period of time
  75892. */
  75893. _this.animations = [];
  75894. _this._imageProcessingConfigurationObserver = null;
  75895. // Values
  75896. _this._sharpenEnabled = false;
  75897. _this._bloomEnabled = false;
  75898. _this._depthOfFieldEnabled = false;
  75899. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75900. _this._fxaaEnabled = false;
  75901. _this._imageProcessingEnabled = true;
  75902. _this._bloomScale = 0.5;
  75903. _this._chromaticAberrationEnabled = false;
  75904. _this._grainEnabled = false;
  75905. _this._buildAllowed = true;
  75906. _this._resizeObserver = null;
  75907. _this._hardwareScaleLevel = 1.0;
  75908. _this._bloomKernel = 64;
  75909. /**
  75910. * Specifies the weight of the bloom in the final rendering
  75911. */
  75912. _this._bloomWeight = 0.15;
  75913. /**
  75914. * Specifies the luma threshold for the area that will be blurred by the bloom
  75915. */
  75916. _this._bloomThreshold = 0.9;
  75917. _this._samples = 1;
  75918. _this._hasCleared = false;
  75919. _this._prevPostProcess = null;
  75920. _this._prevPrevPostProcess = null;
  75921. _this._cameras = cameras || scene.cameras;
  75922. _this._originalCameras = _this._cameras.slice();
  75923. _this._buildAllowed = automaticBuild;
  75924. // Initialize
  75925. _this._scene = scene;
  75926. var caps = _this._scene.getEngine().getCaps();
  75927. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75928. // Misc
  75929. if (_this._hdr) {
  75930. if (caps.textureHalfFloatRender) {
  75931. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75932. }
  75933. else if (caps.textureFloatRender) {
  75934. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75935. }
  75936. }
  75937. else {
  75938. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75939. }
  75940. // Attach
  75941. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75942. var engine = _this._scene.getEngine();
  75943. // Create post processes before hand so they can be modified before enabled.
  75944. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75945. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75946. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75947. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75948. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75949. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75950. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75951. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75952. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75953. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75954. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75955. _this.bloomKernel = _this.bloomKernel;
  75956. });
  75957. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75958. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75959. });
  75960. _this._buildPipeline();
  75961. return _this;
  75962. }
  75963. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75964. get: function () {
  75965. return this._sharpenEnabled;
  75966. },
  75967. /**
  75968. * Enable or disable the sharpen process from the pipeline
  75969. */
  75970. set: function (enabled) {
  75971. if (this._sharpenEnabled === enabled) {
  75972. return;
  75973. }
  75974. this._sharpenEnabled = enabled;
  75975. this._buildPipeline();
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75981. /**
  75982. * Specifies the size of the bloom blur kernel, relative to the final output size
  75983. */
  75984. get: function () {
  75985. return this._bloomKernel;
  75986. },
  75987. set: function (value) {
  75988. this._bloomKernel = value;
  75989. this.bloom.kernel = value / this._hardwareScaleLevel;
  75990. },
  75991. enumerable: true,
  75992. configurable: true
  75993. });
  75994. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75995. get: function () {
  75996. return this._bloomWeight;
  75997. },
  75998. /**
  75999. * The strength of the bloom.
  76000. */
  76001. set: function (value) {
  76002. if (this._bloomWeight === value) {
  76003. return;
  76004. }
  76005. this.bloom.weight = value;
  76006. this._bloomWeight = value;
  76007. },
  76008. enumerable: true,
  76009. configurable: true
  76010. });
  76011. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76012. get: function () {
  76013. return this._bloomThreshold;
  76014. },
  76015. /**
  76016. * The strength of the bloom.
  76017. */
  76018. set: function (value) {
  76019. if (this._bloomThreshold === value) {
  76020. return;
  76021. }
  76022. this.bloom.threshold = value;
  76023. this._bloomThreshold = value;
  76024. },
  76025. enumerable: true,
  76026. configurable: true
  76027. });
  76028. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76029. get: function () {
  76030. return this._bloomScale;
  76031. },
  76032. /**
  76033. * The scale of the bloom, lower value will provide better performance.
  76034. */
  76035. set: function (value) {
  76036. if (this._bloomScale === value) {
  76037. return;
  76038. }
  76039. this._bloomScale = value;
  76040. // recreate bloom and dispose old as this setting is not dynamic
  76041. this._rebuildBloom();
  76042. this._buildPipeline();
  76043. },
  76044. enumerable: true,
  76045. configurable: true
  76046. });
  76047. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76048. get: function () {
  76049. return this._bloomEnabled;
  76050. },
  76051. /**
  76052. * Enable or disable the bloom from the pipeline
  76053. */
  76054. set: function (enabled) {
  76055. if (this._bloomEnabled === enabled) {
  76056. return;
  76057. }
  76058. this._bloomEnabled = enabled;
  76059. this._buildPipeline();
  76060. },
  76061. enumerable: true,
  76062. configurable: true
  76063. });
  76064. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76065. // recreate bloom and dispose old as this setting is not dynamic
  76066. var oldBloom = this.bloom;
  76067. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76068. this.bloom.threshold = oldBloom.threshold;
  76069. for (var i = 0; i < this._cameras.length; i++) {
  76070. oldBloom.disposeEffects(this._cameras[i]);
  76071. }
  76072. };
  76073. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76074. /**
  76075. * If the depth of field is enabled.
  76076. */
  76077. get: function () {
  76078. return this._depthOfFieldEnabled;
  76079. },
  76080. set: function (enabled) {
  76081. if (this._depthOfFieldEnabled === enabled) {
  76082. return;
  76083. }
  76084. this._depthOfFieldEnabled = enabled;
  76085. this._buildPipeline();
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76091. /**
  76092. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76093. */
  76094. get: function () {
  76095. return this._depthOfFieldBlurLevel;
  76096. },
  76097. set: function (value) {
  76098. if (this._depthOfFieldBlurLevel === value) {
  76099. return;
  76100. }
  76101. this._depthOfFieldBlurLevel = value;
  76102. // recreate dof and dispose old as this setting is not dynamic
  76103. var oldDof = this.depthOfField;
  76104. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76105. this.depthOfField.focalLength = oldDof.focalLength;
  76106. this.depthOfField.focusDistance = oldDof.focusDistance;
  76107. this.depthOfField.fStop = oldDof.fStop;
  76108. this.depthOfField.lensSize = oldDof.lensSize;
  76109. for (var i = 0; i < this._cameras.length; i++) {
  76110. oldDof.disposeEffects(this._cameras[i]);
  76111. }
  76112. this._buildPipeline();
  76113. },
  76114. enumerable: true,
  76115. configurable: true
  76116. });
  76117. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76118. get: function () {
  76119. return this._fxaaEnabled;
  76120. },
  76121. /**
  76122. * If the anti aliasing is enabled.
  76123. */
  76124. set: function (enabled) {
  76125. if (this._fxaaEnabled === enabled) {
  76126. return;
  76127. }
  76128. this._fxaaEnabled = enabled;
  76129. this._buildPipeline();
  76130. },
  76131. enumerable: true,
  76132. configurable: true
  76133. });
  76134. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76135. get: function () {
  76136. return this._samples;
  76137. },
  76138. /**
  76139. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76140. */
  76141. set: function (sampleCount) {
  76142. if (this._samples === sampleCount) {
  76143. return;
  76144. }
  76145. this._samples = sampleCount;
  76146. this._buildPipeline();
  76147. },
  76148. enumerable: true,
  76149. configurable: true
  76150. });
  76151. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76152. get: function () {
  76153. return this._imageProcessingEnabled;
  76154. },
  76155. /**
  76156. * If image processing is enabled.
  76157. */
  76158. set: function (enabled) {
  76159. if (this._imageProcessingEnabled === enabled) {
  76160. return;
  76161. }
  76162. this._imageProcessingEnabled = enabled;
  76163. this._buildPipeline();
  76164. },
  76165. enumerable: true,
  76166. configurable: true
  76167. });
  76168. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76169. get: function () {
  76170. return this._glowLayer == null;
  76171. },
  76172. /**
  76173. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76174. */
  76175. set: function (enabled) {
  76176. if (enabled && !this._glowLayer) {
  76177. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76178. }
  76179. else if (!enabled && this._glowLayer) {
  76180. this._glowLayer.dispose();
  76181. this._glowLayer = null;
  76182. }
  76183. },
  76184. enumerable: true,
  76185. configurable: true
  76186. });
  76187. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76188. get: function () {
  76189. return this._chromaticAberrationEnabled;
  76190. },
  76191. /**
  76192. * Enable or disable the chromaticAberration process from the pipeline
  76193. */
  76194. set: function (enabled) {
  76195. if (this._chromaticAberrationEnabled === enabled) {
  76196. return;
  76197. }
  76198. this._chromaticAberrationEnabled = enabled;
  76199. this._buildPipeline();
  76200. },
  76201. enumerable: true,
  76202. configurable: true
  76203. });
  76204. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76205. get: function () {
  76206. return this._grainEnabled;
  76207. },
  76208. /**
  76209. * Enable or disable the grain process from the pipeline
  76210. */
  76211. set: function (enabled) {
  76212. if (this._grainEnabled === enabled) {
  76213. return;
  76214. }
  76215. this._grainEnabled = enabled;
  76216. this._buildPipeline();
  76217. },
  76218. enumerable: true,
  76219. configurable: true
  76220. });
  76221. /**
  76222. * Force the compilation of the entire pipeline.
  76223. */
  76224. DefaultRenderingPipeline.prototype.prepare = function () {
  76225. var previousState = this._buildAllowed;
  76226. this._buildAllowed = true;
  76227. this._buildPipeline();
  76228. this._buildAllowed = previousState;
  76229. };
  76230. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76231. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76232. if (this._hasCleared) {
  76233. postProcess.autoClear = false;
  76234. }
  76235. else {
  76236. postProcess.autoClear = true;
  76237. this._scene.autoClear = false;
  76238. this._hasCleared = true;
  76239. }
  76240. if (!skipTextureSharing) {
  76241. if (this._prevPrevPostProcess) {
  76242. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76243. }
  76244. else {
  76245. postProcess.useOwnOutput();
  76246. }
  76247. if (this._prevPostProcess) {
  76248. this._prevPrevPostProcess = this._prevPostProcess;
  76249. }
  76250. this._prevPostProcess = postProcess;
  76251. }
  76252. };
  76253. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76254. var _this = this;
  76255. if (!this._buildAllowed) {
  76256. return;
  76257. }
  76258. this._scene.autoClear = true;
  76259. var engine = this._scene.getEngine();
  76260. this._disposePostProcesses();
  76261. if (this._cameras !== null) {
  76262. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76263. // get back cameras to be used to reattach pipeline
  76264. this._cameras = this._originalCameras.slice();
  76265. }
  76266. this._reset();
  76267. this._prevPostProcess = null;
  76268. this._prevPrevPostProcess = null;
  76269. this._hasCleared = false;
  76270. if (this.depthOfFieldEnabled) {
  76271. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76272. this.depthOfField.depthTexture = depthTexture;
  76273. if (!this.depthOfField._isReady()) {
  76274. this.depthOfField._updateEffects();
  76275. }
  76276. this.addEffect(this.depthOfField);
  76277. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76278. }
  76279. if (this.bloomEnabled) {
  76280. if (!this.bloom._isReady()) {
  76281. this.bloom._updateEffects();
  76282. }
  76283. this.addEffect(this.bloom);
  76284. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76285. }
  76286. if (this._imageProcessingEnabled) {
  76287. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76288. if (this._hdr) {
  76289. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76290. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76291. }
  76292. else {
  76293. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76294. }
  76295. }
  76296. if (this.sharpenEnabled) {
  76297. if (!this.sharpen.isReady()) {
  76298. this.sharpen.updateEffect();
  76299. }
  76300. this.addEffect(this._sharpenEffect);
  76301. this._setAutoClearAndTextureSharing(this.sharpen);
  76302. }
  76303. if (this.grainEnabled) {
  76304. if (!this.grain.isReady()) {
  76305. this.grain.updateEffect();
  76306. }
  76307. this.addEffect(this._grainEffect);
  76308. this._setAutoClearAndTextureSharing(this.grain);
  76309. }
  76310. if (this.chromaticAberrationEnabled) {
  76311. if (!this.chromaticAberration.isReady()) {
  76312. this.chromaticAberration.updateEffect();
  76313. }
  76314. this.addEffect(this._chromaticAberrationEffect);
  76315. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76316. }
  76317. if (this.fxaaEnabled) {
  76318. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76319. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76320. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76321. }
  76322. if (this._cameras !== null) {
  76323. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76324. }
  76325. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76326. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76327. }
  76328. };
  76329. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76330. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76331. for (var i = 0; i < this._cameras.length; i++) {
  76332. var camera = this._cameras[i];
  76333. if (this.imageProcessing) {
  76334. this.imageProcessing.dispose(camera);
  76335. }
  76336. if (this.fxaa) {
  76337. this.fxaa.dispose(camera);
  76338. }
  76339. // These are created in the constructor and should not be disposed on every pipeline change
  76340. if (disposeNonRecreated) {
  76341. if (this.sharpen) {
  76342. this.sharpen.dispose(camera);
  76343. }
  76344. if (this.depthOfField) {
  76345. this.depthOfField.disposeEffects(camera);
  76346. }
  76347. if (this.bloom) {
  76348. this.bloom.disposeEffects(camera);
  76349. }
  76350. if (this.chromaticAberration) {
  76351. this.chromaticAberration.dispose(camera);
  76352. }
  76353. if (this.grain) {
  76354. this.grain.dispose(camera);
  76355. }
  76356. if (this._glowLayer) {
  76357. this._glowLayer.dispose();
  76358. }
  76359. }
  76360. }
  76361. this.imageProcessing = null;
  76362. this.fxaa = null;
  76363. if (disposeNonRecreated) {
  76364. this.sharpen = null;
  76365. this._sharpenEffect = null;
  76366. this.depthOfField = null;
  76367. this.bloom = null;
  76368. this.chromaticAberration = null;
  76369. this._chromaticAberrationEffect = null;
  76370. this.grain = null;
  76371. this._grainEffect = null;
  76372. this._glowLayer = null;
  76373. }
  76374. };
  76375. /**
  76376. * Dispose of the pipeline and stop all post processes
  76377. */
  76378. DefaultRenderingPipeline.prototype.dispose = function () {
  76379. this._disposePostProcesses(true);
  76380. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76381. this._scene.autoClear = true;
  76382. if (this._resizeObserver) {
  76383. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76384. this._resizeObserver = null;
  76385. }
  76386. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76387. _super.prototype.dispose.call(this);
  76388. };
  76389. /**
  76390. * Serialize the rendering pipeline (Used when exporting)
  76391. * @returns the serialized object
  76392. */
  76393. DefaultRenderingPipeline.prototype.serialize = function () {
  76394. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76395. serializationObject.customType = "DefaultRenderingPipeline";
  76396. return serializationObject;
  76397. };
  76398. /**
  76399. * Parse the serialized pipeline
  76400. * @param source Source pipeline.
  76401. * @param scene The scene to load the pipeline to.
  76402. * @param rootUrl The URL of the serialized pipeline.
  76403. * @returns An instantiated pipeline from the serialized object.
  76404. */
  76405. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76406. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76407. };
  76408. __decorate([
  76409. BABYLON.serialize()
  76410. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76411. __decorate([
  76412. BABYLON.serialize()
  76413. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76414. __decorate([
  76415. BABYLON.serialize()
  76416. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76417. __decorate([
  76418. BABYLON.serialize()
  76419. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76420. __decorate([
  76421. BABYLON.serialize()
  76422. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76423. __decorate([
  76424. BABYLON.serialize()
  76425. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76426. __decorate([
  76427. BABYLON.serialize()
  76428. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76429. __decorate([
  76430. BABYLON.serialize()
  76431. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76432. __decorate([
  76433. BABYLON.serialize()
  76434. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76435. __decorate([
  76436. BABYLON.serialize()
  76437. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76438. __decorate([
  76439. BABYLON.serialize()
  76440. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76441. __decorate([
  76442. BABYLON.serialize()
  76443. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76444. __decorate([
  76445. BABYLON.serialize()
  76446. ], DefaultRenderingPipeline.prototype, "samples", null);
  76447. __decorate([
  76448. BABYLON.serialize()
  76449. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76450. __decorate([
  76451. BABYLON.serialize()
  76452. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76453. __decorate([
  76454. BABYLON.serialize()
  76455. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76456. __decorate([
  76457. BABYLON.serialize()
  76458. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76459. return DefaultRenderingPipeline;
  76460. }(BABYLON.PostProcessRenderPipeline));
  76461. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76462. })(BABYLON || (BABYLON = {}));
  76463. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76464. var BABYLON;
  76465. (function (BABYLON) {
  76466. /**
  76467. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76468. */
  76469. var GeometryBufferRenderer = /** @class */ (function () {
  76470. /**
  76471. * Creates a new G Buffer for the scene
  76472. * @param scene The scene the buffer belongs to
  76473. * @param ratio How big is the buffer related to the main canvas.
  76474. */
  76475. function GeometryBufferRenderer(scene, ratio) {
  76476. if (ratio === void 0) { ratio = 1; }
  76477. this._enablePosition = false;
  76478. this._scene = scene;
  76479. this._ratio = ratio;
  76480. // Render target
  76481. this._createRenderTargets();
  76482. }
  76483. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76484. /**
  76485. * Set the render list (meshes to be rendered) used in the G buffer.
  76486. */
  76487. set: function (meshes) {
  76488. this._multiRenderTarget.renderList = meshes;
  76489. },
  76490. enumerable: true,
  76491. configurable: true
  76492. });
  76493. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76494. /**
  76495. * Gets wether or not G buffer are supported by the running hardware.
  76496. * This requires draw buffer supports
  76497. */
  76498. get: function () {
  76499. return this._multiRenderTarget.isSupported;
  76500. },
  76501. enumerable: true,
  76502. configurable: true
  76503. });
  76504. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76505. /**
  76506. * Gets wether or not position are enabled for the G buffer.
  76507. */
  76508. get: function () {
  76509. return this._enablePosition;
  76510. },
  76511. /**
  76512. * Sets wether or not position are enabled for the G buffer.
  76513. */
  76514. set: function (enable) {
  76515. this._enablePosition = enable;
  76516. this.dispose();
  76517. this._createRenderTargets();
  76518. },
  76519. enumerable: true,
  76520. configurable: true
  76521. });
  76522. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76523. /**
  76524. * Gets the scene associated with the buffer.
  76525. */
  76526. get: function () {
  76527. return this._scene;
  76528. },
  76529. enumerable: true,
  76530. configurable: true
  76531. });
  76532. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76533. /**
  76534. * Gets the ratio used by the buffer during its creation.
  76535. * How big is the buffer related to the main canvas.
  76536. */
  76537. get: function () {
  76538. return this._ratio;
  76539. },
  76540. enumerable: true,
  76541. configurable: true
  76542. });
  76543. /**
  76544. * Checks wether everything is ready to render a submesh to the G buffer.
  76545. * @param subMesh the submesh to check readiness for
  76546. * @param useInstances is the mesh drawn using instance or not
  76547. * @returns true if ready otherwise false
  76548. */
  76549. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76550. var material = subMesh.getMaterial();
  76551. if (material && material.disableDepthWrite) {
  76552. return false;
  76553. }
  76554. var defines = [];
  76555. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76556. var mesh = subMesh.getMesh();
  76557. // Alpha test
  76558. if (material && material.needAlphaTesting()) {
  76559. defines.push("#define ALPHATEST");
  76560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76561. attribs.push(BABYLON.VertexBuffer.UVKind);
  76562. defines.push("#define UV1");
  76563. }
  76564. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76565. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76566. defines.push("#define UV2");
  76567. }
  76568. }
  76569. // Buffers
  76570. if (this._enablePosition) {
  76571. defines.push("#define POSITION");
  76572. }
  76573. // Bones
  76574. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76577. if (mesh.numBoneInfluencers > 4) {
  76578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76580. }
  76581. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76582. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76583. }
  76584. else {
  76585. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76586. }
  76587. // Instances
  76588. if (useInstances) {
  76589. defines.push("#define INSTANCES");
  76590. attribs.push("world0");
  76591. attribs.push("world1");
  76592. attribs.push("world2");
  76593. attribs.push("world3");
  76594. }
  76595. // Get correct effect
  76596. var join = defines.join("\n");
  76597. if (this._cachedDefines !== join) {
  76598. this._cachedDefines = join;
  76599. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76600. }
  76601. return this._effect.isReady();
  76602. };
  76603. /**
  76604. * Gets the current underlying G Buffer.
  76605. * @returns the buffer
  76606. */
  76607. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76608. return this._multiRenderTarget;
  76609. };
  76610. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76611. /**
  76612. * Gets the number of samples used to render the buffer (anti aliasing).
  76613. */
  76614. get: function () {
  76615. return this._multiRenderTarget.samples;
  76616. },
  76617. /**
  76618. * Sets the number of samples used to render the buffer (anti aliasing).
  76619. */
  76620. set: function (value) {
  76621. this._multiRenderTarget.samples = value;
  76622. },
  76623. enumerable: true,
  76624. configurable: true
  76625. });
  76626. /**
  76627. * Disposes the renderer and frees up associated resources.
  76628. */
  76629. GeometryBufferRenderer.prototype.dispose = function () {
  76630. this.getGBuffer().dispose();
  76631. };
  76632. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76633. var _this = this;
  76634. var engine = this._scene.getEngine();
  76635. var count = this._enablePosition ? 3 : 2;
  76636. 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 });
  76637. if (!this.isSupported) {
  76638. return;
  76639. }
  76640. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76641. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76642. this._multiRenderTarget.refreshRate = 1;
  76643. this._multiRenderTarget.renderParticles = false;
  76644. this._multiRenderTarget.renderList = null;
  76645. // set default depth value to 1.0 (far away)
  76646. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76647. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76648. });
  76649. // Custom render function
  76650. var renderSubMesh = function (subMesh) {
  76651. var mesh = subMesh.getRenderingMesh();
  76652. var scene = _this._scene;
  76653. var engine = scene.getEngine();
  76654. var material = subMesh.getMaterial();
  76655. if (!material) {
  76656. return;
  76657. }
  76658. // Culling
  76659. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76660. // Managing instances
  76661. var batch = mesh._getInstancesRenderList(subMesh._id);
  76662. if (batch.mustReturn) {
  76663. return;
  76664. }
  76665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76666. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76667. engine.enableEffect(_this._effect);
  76668. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76669. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76670. _this._effect.setMatrix("view", scene.getViewMatrix());
  76671. // Alpha test
  76672. if (material && material.needAlphaTesting()) {
  76673. var alphaTexture = material.getAlphaTestTexture();
  76674. if (alphaTexture) {
  76675. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76676. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76677. }
  76678. }
  76679. // Bones
  76680. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76681. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76682. }
  76683. // Draw
  76684. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76685. }
  76686. };
  76687. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76688. var index;
  76689. if (depthOnlySubMeshes.length) {
  76690. engine.setColorWrite(false);
  76691. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76692. renderSubMesh(depthOnlySubMeshes.data[index]);
  76693. }
  76694. engine.setColorWrite(true);
  76695. }
  76696. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76697. renderSubMesh(opaqueSubMeshes.data[index]);
  76698. }
  76699. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76700. renderSubMesh(alphaTestSubMeshes.data[index]);
  76701. }
  76702. };
  76703. };
  76704. return GeometryBufferRenderer;
  76705. }());
  76706. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76707. })(BABYLON || (BABYLON = {}));
  76708. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76709. var BABYLON;
  76710. (function (BABYLON) {
  76711. /**
  76712. * This groups together the common properties used for image processing either in direct forward pass
  76713. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76714. * or not.
  76715. */
  76716. var ImageProcessingConfiguration = /** @class */ (function () {
  76717. function ImageProcessingConfiguration() {
  76718. /**
  76719. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76720. */
  76721. this.colorCurves = new BABYLON.ColorCurves();
  76722. this._colorCurvesEnabled = false;
  76723. this._colorGradingEnabled = false;
  76724. this._colorGradingWithGreenDepth = true;
  76725. this._colorGradingBGR = true;
  76726. this._exposure = 1.0;
  76727. this._toneMappingEnabled = false;
  76728. this._contrast = 1.0;
  76729. /**
  76730. * Vignette stretch size.
  76731. */
  76732. this.vignetteStretch = 0;
  76733. /**
  76734. * Vignette centre X Offset.
  76735. */
  76736. this.vignetteCentreX = 0;
  76737. /**
  76738. * Vignette centre Y Offset.
  76739. */
  76740. this.vignetteCentreY = 0;
  76741. /**
  76742. * Vignette weight or intensity of the vignette effect.
  76743. */
  76744. this.vignetteWeight = 1.5;
  76745. /**
  76746. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76747. * if vignetteEnabled is set to true.
  76748. */
  76749. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76750. /**
  76751. * Camera field of view used by the Vignette effect.
  76752. */
  76753. this.vignetteCameraFov = 0.5;
  76754. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76755. this._vignetteEnabled = false;
  76756. this._applyByPostProcess = false;
  76757. this._isEnabled = true;
  76758. /**
  76759. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76760. */
  76761. this.onUpdateParameters = new BABYLON.Observable();
  76762. }
  76763. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76764. /**
  76765. * Gets wether the color curves effect is enabled.
  76766. */
  76767. get: function () {
  76768. return this._colorCurvesEnabled;
  76769. },
  76770. /**
  76771. * Sets wether the color curves effect is enabled.
  76772. */
  76773. set: function (value) {
  76774. if (this._colorCurvesEnabled === value) {
  76775. return;
  76776. }
  76777. this._colorCurvesEnabled = value;
  76778. this._updateParameters();
  76779. },
  76780. enumerable: true,
  76781. configurable: true
  76782. });
  76783. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76784. /**
  76785. * Gets wether the color grading effect is enabled.
  76786. */
  76787. get: function () {
  76788. return this._colorGradingEnabled;
  76789. },
  76790. /**
  76791. * Sets wether the color grading effect is enabled.
  76792. */
  76793. set: function (value) {
  76794. if (this._colorGradingEnabled === value) {
  76795. return;
  76796. }
  76797. this._colorGradingEnabled = value;
  76798. this._updateParameters();
  76799. },
  76800. enumerable: true,
  76801. configurable: true
  76802. });
  76803. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76804. /**
  76805. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76806. */
  76807. get: function () {
  76808. return this._colorGradingWithGreenDepth;
  76809. },
  76810. /**
  76811. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76812. */
  76813. set: function (value) {
  76814. if (this._colorGradingWithGreenDepth === value) {
  76815. return;
  76816. }
  76817. this._colorGradingWithGreenDepth = value;
  76818. this._updateParameters();
  76819. },
  76820. enumerable: true,
  76821. configurable: true
  76822. });
  76823. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76824. /**
  76825. * Gets wether the color grading texture contains BGR values.
  76826. */
  76827. get: function () {
  76828. return this._colorGradingBGR;
  76829. },
  76830. /**
  76831. * Sets wether the color grading texture contains BGR values.
  76832. */
  76833. set: function (value) {
  76834. if (this._colorGradingBGR === value) {
  76835. return;
  76836. }
  76837. this._colorGradingBGR = value;
  76838. this._updateParameters();
  76839. },
  76840. enumerable: true,
  76841. configurable: true
  76842. });
  76843. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76844. /**
  76845. * Gets the Exposure used in the effect.
  76846. */
  76847. get: function () {
  76848. return this._exposure;
  76849. },
  76850. /**
  76851. * Sets the Exposure used in the effect.
  76852. */
  76853. set: function (value) {
  76854. if (this._exposure === value) {
  76855. return;
  76856. }
  76857. this._exposure = value;
  76858. this._updateParameters();
  76859. },
  76860. enumerable: true,
  76861. configurable: true
  76862. });
  76863. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76864. /**
  76865. * Gets wether the tone mapping effect is enabled.
  76866. */
  76867. get: function () {
  76868. return this._toneMappingEnabled;
  76869. },
  76870. /**
  76871. * Sets wether the tone mapping effect is enabled.
  76872. */
  76873. set: function (value) {
  76874. if (this._toneMappingEnabled === value) {
  76875. return;
  76876. }
  76877. this._toneMappingEnabled = value;
  76878. this._updateParameters();
  76879. },
  76880. enumerable: true,
  76881. configurable: true
  76882. });
  76883. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76884. /**
  76885. * Gets the contrast used in the effect.
  76886. */
  76887. get: function () {
  76888. return this._contrast;
  76889. },
  76890. /**
  76891. * Sets the contrast used in the effect.
  76892. */
  76893. set: function (value) {
  76894. if (this._contrast === value) {
  76895. return;
  76896. }
  76897. this._contrast = value;
  76898. this._updateParameters();
  76899. },
  76900. enumerable: true,
  76901. configurable: true
  76902. });
  76903. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76904. /**
  76905. * Gets the vignette blend mode allowing different kind of effect.
  76906. */
  76907. get: function () {
  76908. return this._vignetteBlendMode;
  76909. },
  76910. /**
  76911. * Sets the vignette blend mode allowing different kind of effect.
  76912. */
  76913. set: function (value) {
  76914. if (this._vignetteBlendMode === value) {
  76915. return;
  76916. }
  76917. this._vignetteBlendMode = value;
  76918. this._updateParameters();
  76919. },
  76920. enumerable: true,
  76921. configurable: true
  76922. });
  76923. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76924. /**
  76925. * Gets wether the vignette effect is enabled.
  76926. */
  76927. get: function () {
  76928. return this._vignetteEnabled;
  76929. },
  76930. /**
  76931. * Sets wether the vignette effect is enabled.
  76932. */
  76933. set: function (value) {
  76934. if (this._vignetteEnabled === value) {
  76935. return;
  76936. }
  76937. this._vignetteEnabled = value;
  76938. this._updateParameters();
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76944. /**
  76945. * Gets wether the image processing is applied through a post process or not.
  76946. */
  76947. get: function () {
  76948. return this._applyByPostProcess;
  76949. },
  76950. /**
  76951. * Sets wether the image processing is applied through a post process or not.
  76952. */
  76953. set: function (value) {
  76954. if (this._applyByPostProcess === value) {
  76955. return;
  76956. }
  76957. this._applyByPostProcess = value;
  76958. this._updateParameters();
  76959. },
  76960. enumerable: true,
  76961. configurable: true
  76962. });
  76963. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76964. /**
  76965. * Gets wether the image processing is enabled or not.
  76966. */
  76967. get: function () {
  76968. return this._isEnabled;
  76969. },
  76970. /**
  76971. * Sets wether the image processing is enabled or not.
  76972. */
  76973. set: function (value) {
  76974. if (this._isEnabled === value) {
  76975. return;
  76976. }
  76977. this._isEnabled = value;
  76978. this._updateParameters();
  76979. },
  76980. enumerable: true,
  76981. configurable: true
  76982. });
  76983. /**
  76984. * Method called each time the image processing information changes requires to recompile the effect.
  76985. */
  76986. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76987. this.onUpdateParameters.notifyObservers(this);
  76988. };
  76989. ImageProcessingConfiguration.prototype.getClassName = function () {
  76990. return "ImageProcessingConfiguration";
  76991. };
  76992. /**
  76993. * Prepare the list of uniforms associated with the Image Processing effects.
  76994. * @param uniformsList The list of uniforms used in the effect
  76995. * @param defines the list of defines currently in use
  76996. */
  76997. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76998. if (defines.EXPOSURE) {
  76999. uniforms.push("exposureLinear");
  77000. }
  77001. if (defines.CONTRAST) {
  77002. uniforms.push("contrast");
  77003. }
  77004. if (defines.COLORGRADING) {
  77005. uniforms.push("colorTransformSettings");
  77006. }
  77007. if (defines.VIGNETTE) {
  77008. uniforms.push("vInverseScreenSize");
  77009. uniforms.push("vignetteSettings1");
  77010. uniforms.push("vignetteSettings2");
  77011. }
  77012. if (defines.COLORCURVES) {
  77013. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77014. }
  77015. };
  77016. /**
  77017. * Prepare the list of samplers associated with the Image Processing effects.
  77018. * @param uniformsList The list of uniforms used in the effect
  77019. * @param defines the list of defines currently in use
  77020. */
  77021. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77022. if (defines.COLORGRADING) {
  77023. samplersList.push("txColorTransform");
  77024. }
  77025. };
  77026. /**
  77027. * Prepare the list of defines associated to the shader.
  77028. * @param defines the list of defines to complete
  77029. */
  77030. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77031. if (forPostProcess === void 0) { forPostProcess = false; }
  77032. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77033. defines.VIGNETTE = false;
  77034. defines.TONEMAPPING = false;
  77035. defines.CONTRAST = false;
  77036. defines.EXPOSURE = false;
  77037. defines.COLORCURVES = false;
  77038. defines.COLORGRADING = false;
  77039. defines.COLORGRADING3D = false;
  77040. defines.IMAGEPROCESSING = false;
  77041. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77042. return;
  77043. }
  77044. defines.VIGNETTE = this.vignetteEnabled;
  77045. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77046. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77047. defines.TONEMAPPING = this.toneMappingEnabled;
  77048. defines.CONTRAST = (this.contrast !== 1.0);
  77049. defines.EXPOSURE = (this.exposure !== 1.0);
  77050. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77051. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77052. if (defines.COLORGRADING) {
  77053. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77054. }
  77055. else {
  77056. defines.COLORGRADING3D = false;
  77057. }
  77058. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77059. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77060. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77061. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77062. };
  77063. /**
  77064. * Returns true if all the image processing information are ready.
  77065. */
  77066. ImageProcessingConfiguration.prototype.isReady = function () {
  77067. // Color Grading texure can not be none blocking.
  77068. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77069. };
  77070. /**
  77071. * Binds the image processing to the shader.
  77072. * @param effect The effect to bind to
  77073. */
  77074. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77075. if (aspectRatio === void 0) { aspectRatio = 1; }
  77076. // Color Curves
  77077. if (this._colorCurvesEnabled && this.colorCurves) {
  77078. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77079. }
  77080. // Vignette
  77081. if (this._vignetteEnabled) {
  77082. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77083. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77084. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77085. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77086. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77087. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77088. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77089. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77090. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77091. var vignettePower = -2.0 * this.vignetteWeight;
  77092. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77093. }
  77094. // Exposure
  77095. effect.setFloat("exposureLinear", this.exposure);
  77096. // Contrast
  77097. effect.setFloat("contrast", this.contrast);
  77098. // Color transform settings
  77099. if (this.colorGradingTexture) {
  77100. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77101. var textureSize = this.colorGradingTexture.getSize().height;
  77102. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77103. 0.5 / textureSize, // textureOffset
  77104. textureSize, // textureSize
  77105. this.colorGradingTexture.level // weight
  77106. );
  77107. }
  77108. };
  77109. /**
  77110. * Clones the current image processing instance.
  77111. * @return The cloned image processing
  77112. */
  77113. ImageProcessingConfiguration.prototype.clone = function () {
  77114. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77115. };
  77116. /**
  77117. * Serializes the current image processing instance to a json representation.
  77118. * @return a JSON representation
  77119. */
  77120. ImageProcessingConfiguration.prototype.serialize = function () {
  77121. return BABYLON.SerializationHelper.Serialize(this);
  77122. };
  77123. /**
  77124. * Parses the image processing from a json representation.
  77125. * @param source the JSON source to parse
  77126. * @return The parsed image processing
  77127. */
  77128. ImageProcessingConfiguration.Parse = function (source) {
  77129. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77130. };
  77131. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77132. /**
  77133. * Used to apply the vignette as a mix with the pixel color.
  77134. */
  77135. get: function () {
  77136. return this._VIGNETTEMODE_MULTIPLY;
  77137. },
  77138. enumerable: true,
  77139. configurable: true
  77140. });
  77141. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77142. /**
  77143. * Used to apply the vignette as a replacement of the pixel color.
  77144. */
  77145. get: function () {
  77146. return this._VIGNETTEMODE_OPAQUE;
  77147. },
  77148. enumerable: true,
  77149. configurable: true
  77150. });
  77151. // Static constants associated to the image processing.
  77152. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77153. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77154. __decorate([
  77155. BABYLON.serializeAsColorCurves()
  77156. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77157. __decorate([
  77158. BABYLON.serialize()
  77159. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77160. __decorate([
  77161. BABYLON.serializeAsTexture()
  77162. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77163. __decorate([
  77164. BABYLON.serialize()
  77165. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77166. __decorate([
  77167. BABYLON.serialize()
  77168. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77169. __decorate([
  77170. BABYLON.serialize()
  77171. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77172. __decorate([
  77173. BABYLON.serialize()
  77174. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77175. __decorate([
  77176. BABYLON.serialize()
  77177. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77178. __decorate([
  77179. BABYLON.serialize()
  77180. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77181. __decorate([
  77182. BABYLON.serialize()
  77183. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77184. __decorate([
  77185. BABYLON.serialize()
  77186. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77187. __decorate([
  77188. BABYLON.serialize()
  77189. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77190. __decorate([
  77191. BABYLON.serialize()
  77192. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77193. __decorate([
  77194. BABYLON.serializeAsColor4()
  77195. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77196. __decorate([
  77197. BABYLON.serialize()
  77198. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77199. __decorate([
  77200. BABYLON.serialize()
  77201. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77202. __decorate([
  77203. BABYLON.serialize()
  77204. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77205. __decorate([
  77206. BABYLON.serialize()
  77207. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77208. __decorate([
  77209. BABYLON.serialize()
  77210. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77211. return ImageProcessingConfiguration;
  77212. }());
  77213. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77214. })(BABYLON || (BABYLON = {}));
  77215. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77216. var BABYLON;
  77217. (function (BABYLON) {
  77218. /**
  77219. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77220. * It can help converting any input color in a desired output one. This can then be used to create effects
  77221. * from sepia, black and white to sixties or futuristic rendering...
  77222. *
  77223. * The only supported format is currently 3dl.
  77224. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77225. */
  77226. var ColorGradingTexture = /** @class */ (function (_super) {
  77227. __extends(ColorGradingTexture, _super);
  77228. /**
  77229. * Instantiates a ColorGradingTexture from the following parameters.
  77230. *
  77231. * @param url The location of the color gradind data (currently only supporting 3dl)
  77232. * @param scene The scene the texture will be used in
  77233. */
  77234. function ColorGradingTexture(url, scene) {
  77235. var _this = _super.call(this, scene) || this;
  77236. if (!url) {
  77237. return _this;
  77238. }
  77239. _this._engine = scene.getEngine();
  77240. _this._textureMatrix = BABYLON.Matrix.Identity();
  77241. _this.name = url;
  77242. _this.url = url;
  77243. _this.hasAlpha = false;
  77244. _this.isCube = false;
  77245. _this.is3D = _this._engine.webGLVersion > 1;
  77246. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77247. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77248. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77249. _this.anisotropicFilteringLevel = 1;
  77250. _this._texture = _this._getFromCache(url, true);
  77251. if (!_this._texture) {
  77252. if (!scene.useDelayedTextureLoading) {
  77253. _this.loadTexture();
  77254. }
  77255. else {
  77256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77257. }
  77258. }
  77259. return _this;
  77260. }
  77261. /**
  77262. * Returns the texture matrix used in most of the material.
  77263. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77264. */
  77265. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77266. return this._textureMatrix;
  77267. };
  77268. /**
  77269. * Occurs when the file being loaded is a .3dl LUT file.
  77270. */
  77271. ColorGradingTexture.prototype.load3dlTexture = function () {
  77272. var engine = this._engine;
  77273. var texture;
  77274. if (engine.webGLVersion === 1) {
  77275. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77276. }
  77277. else {
  77278. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77279. }
  77280. this._texture = texture;
  77281. var callback = function (text) {
  77282. if (typeof text !== "string") {
  77283. return;
  77284. }
  77285. var data = null;
  77286. var tempData = null;
  77287. var line;
  77288. var lines = text.split('\n');
  77289. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77290. var maxColor = 0;
  77291. for (var i = 0; i < lines.length; i++) {
  77292. line = lines[i];
  77293. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77294. continue;
  77295. if (line.indexOf('#') === 0)
  77296. continue;
  77297. var words = line.split(" ");
  77298. if (size === 0) {
  77299. // Number of space + one
  77300. size = words.length;
  77301. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77302. tempData = new Float32Array(size * size * size * 4);
  77303. continue;
  77304. }
  77305. if (size != 0) {
  77306. var r = Math.max(parseInt(words[0]), 0);
  77307. var g = Math.max(parseInt(words[1]), 0);
  77308. var b = Math.max(parseInt(words[2]), 0);
  77309. maxColor = Math.max(r, maxColor);
  77310. maxColor = Math.max(g, maxColor);
  77311. maxColor = Math.max(b, maxColor);
  77312. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77313. if (tempData) {
  77314. tempData[pixelStorageIndex + 0] = r;
  77315. tempData[pixelStorageIndex + 1] = g;
  77316. tempData[pixelStorageIndex + 2] = b;
  77317. }
  77318. pixelIndexSlice++;
  77319. if (pixelIndexSlice % size == 0) {
  77320. pixelIndexH++;
  77321. pixelIndexSlice = 0;
  77322. if (pixelIndexH % size == 0) {
  77323. pixelIndexW++;
  77324. pixelIndexH = 0;
  77325. }
  77326. }
  77327. }
  77328. }
  77329. if (tempData && data) {
  77330. for (var i = 0; i < tempData.length; i++) {
  77331. if (i > 0 && (i + 1) % 4 === 0) {
  77332. data[i] = 255;
  77333. }
  77334. else {
  77335. var value = tempData[i];
  77336. data[i] = (value / maxColor * 255);
  77337. }
  77338. }
  77339. }
  77340. if (texture.is3D) {
  77341. texture.updateSize(size, size, size);
  77342. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77343. }
  77344. else {
  77345. texture.updateSize(size * size, size);
  77346. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77347. }
  77348. };
  77349. var scene = this.getScene();
  77350. if (scene) {
  77351. scene._loadFile(this.url, callback);
  77352. }
  77353. else {
  77354. this._engine._loadFile(this.url, callback);
  77355. }
  77356. return this._texture;
  77357. };
  77358. /**
  77359. * Starts the loading process of the texture.
  77360. */
  77361. ColorGradingTexture.prototype.loadTexture = function () {
  77362. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77363. this.load3dlTexture();
  77364. }
  77365. };
  77366. /**
  77367. * Clones the color gradind texture.
  77368. */
  77369. ColorGradingTexture.prototype.clone = function () {
  77370. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77371. // Base texture
  77372. newTexture.level = this.level;
  77373. return newTexture;
  77374. };
  77375. /**
  77376. * Called during delayed load for textures.
  77377. */
  77378. ColorGradingTexture.prototype.delayLoad = function () {
  77379. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77380. return;
  77381. }
  77382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77383. this._texture = this._getFromCache(this.url, true);
  77384. if (!this._texture) {
  77385. this.loadTexture();
  77386. }
  77387. };
  77388. /**
  77389. * Parses a color grading texture serialized by Babylon.
  77390. * @param parsedTexture The texture information being parsedTexture
  77391. * @param scene The scene to load the texture in
  77392. * @param rootUrl The root url of the data assets to load
  77393. * @return A color gradind texture
  77394. */
  77395. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77396. var texture = null;
  77397. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77398. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77399. texture.name = parsedTexture.name;
  77400. texture.level = parsedTexture.level;
  77401. }
  77402. return texture;
  77403. };
  77404. /**
  77405. * Serializes the LUT texture to json format.
  77406. */
  77407. ColorGradingTexture.prototype.serialize = function () {
  77408. if (!this.name) {
  77409. return null;
  77410. }
  77411. var serializationObject = {};
  77412. serializationObject.name = this.name;
  77413. serializationObject.level = this.level;
  77414. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77415. return serializationObject;
  77416. };
  77417. /**
  77418. * Empty line regex stored for GC.
  77419. */
  77420. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77421. return ColorGradingTexture;
  77422. }(BABYLON.BaseTexture));
  77423. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77424. })(BABYLON || (BABYLON = {}));
  77425. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77426. var BABYLON;
  77427. (function (BABYLON) {
  77428. /**
  77429. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77430. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77431. * 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;
  77432. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77433. */
  77434. var ColorCurves = /** @class */ (function () {
  77435. function ColorCurves() {
  77436. this._dirty = true;
  77437. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77438. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77439. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77440. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77441. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77442. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77443. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77444. this._globalHue = 30;
  77445. this._globalDensity = 0;
  77446. this._globalSaturation = 0;
  77447. this._globalExposure = 0;
  77448. this._highlightsHue = 30;
  77449. this._highlightsDensity = 0;
  77450. this._highlightsSaturation = 0;
  77451. this._highlightsExposure = 0;
  77452. this._midtonesHue = 30;
  77453. this._midtonesDensity = 0;
  77454. this._midtonesSaturation = 0;
  77455. this._midtonesExposure = 0;
  77456. this._shadowsHue = 30;
  77457. this._shadowsDensity = 0;
  77458. this._shadowsSaturation = 0;
  77459. this._shadowsExposure = 0;
  77460. }
  77461. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77462. /**
  77463. * Gets the global Hue value.
  77464. * 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).
  77465. */
  77466. get: function () {
  77467. return this._globalHue;
  77468. },
  77469. /**
  77470. * Sets the global Hue value.
  77471. * 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).
  77472. */
  77473. set: function (value) {
  77474. this._globalHue = value;
  77475. this._dirty = true;
  77476. },
  77477. enumerable: true,
  77478. configurable: true
  77479. });
  77480. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77481. /**
  77482. * Gets the global Density value.
  77483. * 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.
  77484. * Values less than zero provide a filter of opposite hue.
  77485. */
  77486. get: function () {
  77487. return this._globalDensity;
  77488. },
  77489. /**
  77490. * Sets the global Density value.
  77491. * 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.
  77492. * Values less than zero provide a filter of opposite hue.
  77493. */
  77494. set: function (value) {
  77495. this._globalDensity = value;
  77496. this._dirty = true;
  77497. },
  77498. enumerable: true,
  77499. configurable: true
  77500. });
  77501. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77502. /**
  77503. * Gets the global Saturation value.
  77504. * 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.
  77505. */
  77506. get: function () {
  77507. return this._globalSaturation;
  77508. },
  77509. /**
  77510. * Sets the global Saturation value.
  77511. * 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.
  77512. */
  77513. set: function (value) {
  77514. this._globalSaturation = value;
  77515. this._dirty = true;
  77516. },
  77517. enumerable: true,
  77518. configurable: true
  77519. });
  77520. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77521. /**
  77522. * Gets the global Exposure value.
  77523. * 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.
  77524. */
  77525. get: function () {
  77526. return this._globalExposure;
  77527. },
  77528. /**
  77529. * Sets the global Exposure value.
  77530. * 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.
  77531. */
  77532. set: function (value) {
  77533. this._globalExposure = value;
  77534. this._dirty = true;
  77535. },
  77536. enumerable: true,
  77537. configurable: true
  77538. });
  77539. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77540. /**
  77541. * Gets the highlights Hue value.
  77542. * 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).
  77543. */
  77544. get: function () {
  77545. return this._highlightsHue;
  77546. },
  77547. /**
  77548. * Sets the highlights Hue value.
  77549. * 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).
  77550. */
  77551. set: function (value) {
  77552. this._highlightsHue = value;
  77553. this._dirty = true;
  77554. },
  77555. enumerable: true,
  77556. configurable: true
  77557. });
  77558. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77559. /**
  77560. * Gets the highlights Density value.
  77561. * 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.
  77562. * Values less than zero provide a filter of opposite hue.
  77563. */
  77564. get: function () {
  77565. return this._highlightsDensity;
  77566. },
  77567. /**
  77568. * Sets the highlights Density value.
  77569. * 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.
  77570. * Values less than zero provide a filter of opposite hue.
  77571. */
  77572. set: function (value) {
  77573. this._highlightsDensity = value;
  77574. this._dirty = true;
  77575. },
  77576. enumerable: true,
  77577. configurable: true
  77578. });
  77579. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77580. /**
  77581. * Gets the highlights Saturation value.
  77582. * 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.
  77583. */
  77584. get: function () {
  77585. return this._highlightsSaturation;
  77586. },
  77587. /**
  77588. * Sets the highlights Saturation value.
  77589. * 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.
  77590. */
  77591. set: function (value) {
  77592. this._highlightsSaturation = value;
  77593. this._dirty = true;
  77594. },
  77595. enumerable: true,
  77596. configurable: true
  77597. });
  77598. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77599. /**
  77600. * Gets the highlights Exposure value.
  77601. * 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.
  77602. */
  77603. get: function () {
  77604. return this._highlightsExposure;
  77605. },
  77606. /**
  77607. * Sets the highlights Exposure value.
  77608. * 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.
  77609. */
  77610. set: function (value) {
  77611. this._highlightsExposure = value;
  77612. this._dirty = true;
  77613. },
  77614. enumerable: true,
  77615. configurable: true
  77616. });
  77617. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77618. /**
  77619. * Gets the midtones Hue value.
  77620. * 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).
  77621. */
  77622. get: function () {
  77623. return this._midtonesHue;
  77624. },
  77625. /**
  77626. * Sets the midtones Hue value.
  77627. * 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).
  77628. */
  77629. set: function (value) {
  77630. this._midtonesHue = value;
  77631. this._dirty = true;
  77632. },
  77633. enumerable: true,
  77634. configurable: true
  77635. });
  77636. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77637. /**
  77638. * Gets the midtones Density value.
  77639. * 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.
  77640. * Values less than zero provide a filter of opposite hue.
  77641. */
  77642. get: function () {
  77643. return this._midtonesDensity;
  77644. },
  77645. /**
  77646. * Sets the midtones Density value.
  77647. * 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.
  77648. * Values less than zero provide a filter of opposite hue.
  77649. */
  77650. set: function (value) {
  77651. this._midtonesDensity = value;
  77652. this._dirty = true;
  77653. },
  77654. enumerable: true,
  77655. configurable: true
  77656. });
  77657. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77658. /**
  77659. * Gets the midtones Saturation value.
  77660. * 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.
  77661. */
  77662. get: function () {
  77663. return this._midtonesSaturation;
  77664. },
  77665. /**
  77666. * Sets the midtones Saturation value.
  77667. * 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.
  77668. */
  77669. set: function (value) {
  77670. this._midtonesSaturation = value;
  77671. this._dirty = true;
  77672. },
  77673. enumerable: true,
  77674. configurable: true
  77675. });
  77676. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77677. /**
  77678. * Gets the midtones Exposure value.
  77679. * 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.
  77680. */
  77681. get: function () {
  77682. return this._midtonesExposure;
  77683. },
  77684. /**
  77685. * Sets the midtones Exposure value.
  77686. * 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.
  77687. */
  77688. set: function (value) {
  77689. this._midtonesExposure = value;
  77690. this._dirty = true;
  77691. },
  77692. enumerable: true,
  77693. configurable: true
  77694. });
  77695. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77696. /**
  77697. * Gets the shadows Hue value.
  77698. * 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).
  77699. */
  77700. get: function () {
  77701. return this._shadowsHue;
  77702. },
  77703. /**
  77704. * Sets the shadows Hue value.
  77705. * 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).
  77706. */
  77707. set: function (value) {
  77708. this._shadowsHue = value;
  77709. this._dirty = true;
  77710. },
  77711. enumerable: true,
  77712. configurable: true
  77713. });
  77714. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77715. /**
  77716. * Gets the shadows Density value.
  77717. * 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.
  77718. * Values less than zero provide a filter of opposite hue.
  77719. */
  77720. get: function () {
  77721. return this._shadowsDensity;
  77722. },
  77723. /**
  77724. * Sets the shadows Density value.
  77725. * 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.
  77726. * Values less than zero provide a filter of opposite hue.
  77727. */
  77728. set: function (value) {
  77729. this._shadowsDensity = value;
  77730. this._dirty = true;
  77731. },
  77732. enumerable: true,
  77733. configurable: true
  77734. });
  77735. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77736. /**
  77737. * Gets the shadows Saturation value.
  77738. * 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.
  77739. */
  77740. get: function () {
  77741. return this._shadowsSaturation;
  77742. },
  77743. /**
  77744. * Sets the shadows Saturation value.
  77745. * 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.
  77746. */
  77747. set: function (value) {
  77748. this._shadowsSaturation = value;
  77749. this._dirty = true;
  77750. },
  77751. enumerable: true,
  77752. configurable: true
  77753. });
  77754. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77755. /**
  77756. * Gets the shadows Exposure value.
  77757. * 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.
  77758. */
  77759. get: function () {
  77760. return this._shadowsExposure;
  77761. },
  77762. /**
  77763. * Sets the shadows Exposure value.
  77764. * 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.
  77765. */
  77766. set: function (value) {
  77767. this._shadowsExposure = value;
  77768. this._dirty = true;
  77769. },
  77770. enumerable: true,
  77771. configurable: true
  77772. });
  77773. ColorCurves.prototype.getClassName = function () {
  77774. return "ColorCurves";
  77775. };
  77776. /**
  77777. * Binds the color curves to the shader.
  77778. * @param colorCurves The color curve to bind
  77779. * @param effect The effect to bind to
  77780. */
  77781. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77782. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77783. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77784. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77785. if (colorCurves._dirty) {
  77786. colorCurves._dirty = false;
  77787. // Fill in global info.
  77788. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77789. // Compute highlights info.
  77790. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77791. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77792. // Compute midtones info.
  77793. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77794. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77795. // Compute shadows info.
  77796. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77797. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77798. // Compute deltas (neutral is midtones).
  77799. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77800. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77801. }
  77802. if (effect) {
  77803. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77804. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77805. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77806. }
  77807. };
  77808. /**
  77809. * Prepare the list of uniforms associated with the ColorCurves effects.
  77810. * @param uniformsList The list of uniforms used in the effect
  77811. */
  77812. ColorCurves.PrepareUniforms = function (uniformsList) {
  77813. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77814. };
  77815. /**
  77816. * Returns color grading data based on a hue, density, saturation and exposure value.
  77817. * @param filterHue The hue of the color filter.
  77818. * @param filterDensity The density of the color filter.
  77819. * @param saturation The saturation.
  77820. * @param exposure The exposure.
  77821. * @param result The result data container.
  77822. */
  77823. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77824. if (hue == null) {
  77825. return;
  77826. }
  77827. hue = ColorCurves.clamp(hue, 0, 360);
  77828. density = ColorCurves.clamp(density, -100, 100);
  77829. saturation = ColorCurves.clamp(saturation, -100, 100);
  77830. exposure = ColorCurves.clamp(exposure, -100, 100);
  77831. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77832. // so that the maximum filter density is only 50% control. This provides fine control
  77833. // for small values and reasonable range.
  77834. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77835. density *= 0.5;
  77836. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77837. if (density < 0) {
  77838. density *= -1;
  77839. hue = (hue + 180) % 360;
  77840. }
  77841. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77842. result.scaleToRef(2, result);
  77843. result.a = 1 + 0.01 * saturation;
  77844. };
  77845. /**
  77846. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77847. * @param value The input slider value in range [-100,100].
  77848. * @returns Adjusted value.
  77849. */
  77850. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77851. value /= 100;
  77852. var x = Math.abs(value);
  77853. x = Math.pow(x, 2);
  77854. if (value < 0) {
  77855. x *= -1;
  77856. }
  77857. x *= 100;
  77858. return x;
  77859. };
  77860. /**
  77861. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77862. * @param hue The hue (H) input.
  77863. * @param saturation The saturation (S) input.
  77864. * @param brightness The brightness (B) input.
  77865. * @result An RGBA color represented as Vector4.
  77866. */
  77867. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77868. var h = ColorCurves.clamp(hue, 0, 360);
  77869. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77870. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77871. if (s === 0) {
  77872. result.r = v;
  77873. result.g = v;
  77874. result.b = v;
  77875. }
  77876. else {
  77877. // sector 0 to 5
  77878. h /= 60;
  77879. var i = Math.floor(h);
  77880. // fractional part of h
  77881. var f = h - i;
  77882. var p = v * (1 - s);
  77883. var q = v * (1 - s * f);
  77884. var t = v * (1 - s * (1 - f));
  77885. switch (i) {
  77886. case 0:
  77887. result.r = v;
  77888. result.g = t;
  77889. result.b = p;
  77890. break;
  77891. case 1:
  77892. result.r = q;
  77893. result.g = v;
  77894. result.b = p;
  77895. break;
  77896. case 2:
  77897. result.r = p;
  77898. result.g = v;
  77899. result.b = t;
  77900. break;
  77901. case 3:
  77902. result.r = p;
  77903. result.g = q;
  77904. result.b = v;
  77905. break;
  77906. case 4:
  77907. result.r = t;
  77908. result.g = p;
  77909. result.b = v;
  77910. break;
  77911. default: // case 5:
  77912. result.r = v;
  77913. result.g = p;
  77914. result.b = q;
  77915. break;
  77916. }
  77917. }
  77918. result.a = 1;
  77919. };
  77920. /**
  77921. * Returns a value clamped between min and max
  77922. * @param value The value to clamp
  77923. * @param min The minimum of value
  77924. * @param max The maximum of value
  77925. * @returns The clamped value.
  77926. */
  77927. ColorCurves.clamp = function (value, min, max) {
  77928. return Math.min(Math.max(value, min), max);
  77929. };
  77930. /**
  77931. * Clones the current color curve instance.
  77932. * @return The cloned curves
  77933. */
  77934. ColorCurves.prototype.clone = function () {
  77935. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77936. };
  77937. /**
  77938. * Serializes the current color curve instance to a json representation.
  77939. * @return a JSON representation
  77940. */
  77941. ColorCurves.prototype.serialize = function () {
  77942. return BABYLON.SerializationHelper.Serialize(this);
  77943. };
  77944. /**
  77945. * Parses the color curve from a json representation.
  77946. * @param source the JSON source to parse
  77947. * @return The parsed curves
  77948. */
  77949. ColorCurves.Parse = function (source) {
  77950. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77951. };
  77952. __decorate([
  77953. BABYLON.serialize()
  77954. ], ColorCurves.prototype, "_globalHue", void 0);
  77955. __decorate([
  77956. BABYLON.serialize()
  77957. ], ColorCurves.prototype, "_globalDensity", void 0);
  77958. __decorate([
  77959. BABYLON.serialize()
  77960. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77961. __decorate([
  77962. BABYLON.serialize()
  77963. ], ColorCurves.prototype, "_globalExposure", void 0);
  77964. __decorate([
  77965. BABYLON.serialize()
  77966. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77967. __decorate([
  77968. BABYLON.serialize()
  77969. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77970. __decorate([
  77971. BABYLON.serialize()
  77972. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77973. __decorate([
  77974. BABYLON.serialize()
  77975. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77976. __decorate([
  77977. BABYLON.serialize()
  77978. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77979. __decorate([
  77980. BABYLON.serialize()
  77981. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77982. __decorate([
  77983. BABYLON.serialize()
  77984. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77985. __decorate([
  77986. BABYLON.serialize()
  77987. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77988. return ColorCurves;
  77989. }());
  77990. BABYLON.ColorCurves = ColorCurves;
  77991. })(BABYLON || (BABYLON = {}));
  77992. //# sourceMappingURL=babylon.colorCurves.js.map
  77993. var BABYLON;
  77994. (function (BABYLON) {
  77995. var RefractionPostProcess = /** @class */ (function (_super) {
  77996. __extends(RefractionPostProcess, _super);
  77997. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77998. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77999. _this.color = color;
  78000. _this.depth = depth;
  78001. _this.colorLevel = colorLevel;
  78002. _this._ownRefractionTexture = true;
  78003. _this.onActivateObservable.add(function (cam) {
  78004. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78005. });
  78006. _this.onApplyObservable.add(function (effect) {
  78007. effect.setColor3("baseColor", _this.color);
  78008. effect.setFloat("depth", _this.depth);
  78009. effect.setFloat("colorLevel", _this.colorLevel);
  78010. effect.setTexture("refractionSampler", _this._refTexture);
  78011. });
  78012. return _this;
  78013. }
  78014. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78015. /**
  78016. * Gets or sets the refraction texture
  78017. * Please note that you are responsible for disposing the texture if you set it manually
  78018. */
  78019. get: function () {
  78020. return this._refTexture;
  78021. },
  78022. set: function (value) {
  78023. if (this._refTexture && this._ownRefractionTexture) {
  78024. this._refTexture.dispose();
  78025. }
  78026. this._refTexture = value;
  78027. this._ownRefractionTexture = false;
  78028. },
  78029. enumerable: true,
  78030. configurable: true
  78031. });
  78032. // Methods
  78033. RefractionPostProcess.prototype.dispose = function (camera) {
  78034. if (this._refTexture && this._ownRefractionTexture) {
  78035. this._refTexture.dispose();
  78036. this._refTexture = null;
  78037. }
  78038. _super.prototype.dispose.call(this, camera);
  78039. };
  78040. return RefractionPostProcess;
  78041. }(BABYLON.PostProcess));
  78042. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78043. })(BABYLON || (BABYLON = {}));
  78044. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78045. var BABYLON;
  78046. (function (BABYLON) {
  78047. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78048. __extends(BlackAndWhitePostProcess, _super);
  78049. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78050. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78051. _this.degree = 1;
  78052. _this.onApplyObservable.add(function (effect) {
  78053. effect.setFloat("degree", _this.degree);
  78054. });
  78055. return _this;
  78056. }
  78057. return BlackAndWhitePostProcess;
  78058. }(BABYLON.PostProcess));
  78059. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78060. })(BABYLON || (BABYLON = {}));
  78061. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78062. var BABYLON;
  78063. (function (BABYLON) {
  78064. /**
  78065. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78066. * input texture to perform effects such as edge detection or sharpening
  78067. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78068. */
  78069. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78070. __extends(ConvolutionPostProcess, _super);
  78071. /**
  78072. * Creates a new instance ConvolutionPostProcess
  78073. * @param name The name of the effect.
  78074. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78075. * @param options The required width/height ratio to downsize to before computing the render pass.
  78076. * @param camera The camera to apply the render pass to.
  78077. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78078. * @param engine The engine which the post process will be applied. (default: current engine)
  78079. * @param reusable If the post process can be reused on the same frame. (default: false)
  78080. * @param textureType Type of textures used when performing the post process. (default: 0)
  78081. */
  78082. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78083. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78084. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78085. _this.kernel = kernel;
  78086. _this.onApply = function (effect) {
  78087. effect.setFloat2("screenSize", _this.width, _this.height);
  78088. effect.setArray("kernel", _this.kernel);
  78089. };
  78090. return _this;
  78091. }
  78092. // Statics
  78093. /**
  78094. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78095. */
  78096. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78097. /**
  78098. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78099. */
  78100. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78101. /**
  78102. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78103. */
  78104. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78105. /**
  78106. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78107. */
  78108. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78109. /**
  78110. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78111. */
  78112. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78113. /**
  78114. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78115. */
  78116. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78117. return ConvolutionPostProcess;
  78118. }(BABYLON.PostProcess));
  78119. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78120. })(BABYLON || (BABYLON = {}));
  78121. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78122. var BABYLON;
  78123. (function (BABYLON) {
  78124. var FilterPostProcess = /** @class */ (function (_super) {
  78125. __extends(FilterPostProcess, _super);
  78126. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78127. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78128. _this.kernelMatrix = kernelMatrix;
  78129. _this.onApply = function (effect) {
  78130. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78131. };
  78132. return _this;
  78133. }
  78134. return FilterPostProcess;
  78135. }(BABYLON.PostProcess));
  78136. BABYLON.FilterPostProcess = FilterPostProcess;
  78137. })(BABYLON || (BABYLON = {}));
  78138. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78139. var BABYLON;
  78140. (function (BABYLON) {
  78141. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78142. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78143. __extends(VolumetricLightScatteringPostProcess, _super);
  78144. /**
  78145. * @constructor
  78146. * @param {string} name - The post-process name
  78147. * @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)
  78148. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78149. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78150. * @param {number} samples - The post-process quality, default 100
  78151. * @param {number} samplingMode - The post-process filtering mode
  78152. * @param {BABYLON.Engine} engine - The babylon engine
  78153. * @param {boolean} reusable - If the post-process is reusable
  78154. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78155. */
  78156. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78157. if (samples === void 0) { samples = 100; }
  78158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78159. 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;
  78160. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78161. /**
  78162. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78163. */
  78164. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78165. /**
  78166. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78167. */
  78168. _this.useCustomMeshPosition = false;
  78169. /**
  78170. * If the post-process should inverse the light scattering direction
  78171. */
  78172. _this.invert = true;
  78173. /**
  78174. * Array containing the excluded meshes not rendered in the internal pass
  78175. */
  78176. _this.excludedMeshes = new Array();
  78177. /**
  78178. * Controls the overall intensity of the post-process
  78179. */
  78180. _this.exposure = 0.3;
  78181. /**
  78182. * Dissipates each sample's contribution in range [0, 1]
  78183. */
  78184. _this.decay = 0.96815;
  78185. /**
  78186. * Controls the overall intensity of each sample
  78187. */
  78188. _this.weight = 0.58767;
  78189. /**
  78190. * Controls the density of each sample
  78191. */
  78192. _this.density = 0.926;
  78193. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78194. engine = scene.getEngine();
  78195. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78196. // Configure mesh
  78197. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78198. // Configure
  78199. _this._createPass(scene, ratio.passRatio || ratio);
  78200. _this.onActivate = function (camera) {
  78201. if (!_this.isSupported) {
  78202. _this.dispose(camera);
  78203. }
  78204. _this.onActivate = null;
  78205. };
  78206. _this.onApplyObservable.add(function (effect) {
  78207. _this._updateMeshScreenCoordinates(scene);
  78208. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78209. effect.setFloat("exposure", _this.exposure);
  78210. effect.setFloat("decay", _this.decay);
  78211. effect.setFloat("weight", _this.weight);
  78212. effect.setFloat("density", _this.density);
  78213. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78214. });
  78215. return _this;
  78216. }
  78217. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78218. get: function () {
  78219. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78220. return false;
  78221. },
  78222. set: function (useDiffuseColor) {
  78223. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78224. },
  78225. enumerable: true,
  78226. configurable: true
  78227. });
  78228. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78229. return "VolumetricLightScatteringPostProcess";
  78230. };
  78231. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78232. var mesh = subMesh.getMesh();
  78233. // Render this.mesh as default
  78234. if (mesh === this.mesh && mesh.material) {
  78235. return mesh.material.isReady(mesh);
  78236. }
  78237. var defines = [];
  78238. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78239. var material = subMesh.getMaterial();
  78240. // Alpha test
  78241. if (material) {
  78242. if (material.needAlphaTesting()) {
  78243. defines.push("#define ALPHATEST");
  78244. }
  78245. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78246. attribs.push(BABYLON.VertexBuffer.UVKind);
  78247. defines.push("#define UV1");
  78248. }
  78249. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78250. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78251. defines.push("#define UV2");
  78252. }
  78253. }
  78254. // Bones
  78255. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78259. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78260. }
  78261. else {
  78262. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78263. }
  78264. // Instances
  78265. if (useInstances) {
  78266. defines.push("#define INSTANCES");
  78267. attribs.push("world0");
  78268. attribs.push("world1");
  78269. attribs.push("world2");
  78270. attribs.push("world3");
  78271. }
  78272. // Get correct effect
  78273. var join = defines.join("\n");
  78274. if (this._cachedDefines !== join) {
  78275. this._cachedDefines = join;
  78276. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78277. }
  78278. return this._volumetricLightScatteringPass.isReady();
  78279. };
  78280. /**
  78281. * Sets the new light position for light scattering effect
  78282. * @param {BABYLON.Vector3} The new custom light position
  78283. */
  78284. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78285. this.customMeshPosition = position;
  78286. };
  78287. /**
  78288. * Returns the light position for light scattering effect
  78289. * @return {BABYLON.Vector3} The custom light position
  78290. */
  78291. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78292. return this.customMeshPosition;
  78293. };
  78294. /**
  78295. * Disposes the internal assets and detaches the post-process from the camera
  78296. */
  78297. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78298. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78299. if (rttIndex !== -1) {
  78300. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78301. }
  78302. this._volumetricLightScatteringRTT.dispose();
  78303. _super.prototype.dispose.call(this, camera);
  78304. };
  78305. /**
  78306. * Returns the render target texture used by the post-process
  78307. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78308. */
  78309. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78310. return this._volumetricLightScatteringRTT;
  78311. };
  78312. // Private methods
  78313. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78314. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78315. return true;
  78316. }
  78317. return false;
  78318. };
  78319. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78320. var _this = this;
  78321. var engine = scene.getEngine();
  78322. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78323. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78324. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78325. this._volumetricLightScatteringRTT.renderList = null;
  78326. this._volumetricLightScatteringRTT.renderParticles = false;
  78327. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78328. var camera = this.getCamera();
  78329. if (camera) {
  78330. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78331. }
  78332. else {
  78333. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78334. }
  78335. // Custom render function for submeshes
  78336. var renderSubMesh = function (subMesh) {
  78337. var mesh = subMesh.getRenderingMesh();
  78338. if (_this._meshExcluded(mesh)) {
  78339. return;
  78340. }
  78341. var material = subMesh.getMaterial();
  78342. if (!material) {
  78343. return;
  78344. }
  78345. var scene = mesh.getScene();
  78346. var engine = scene.getEngine();
  78347. // Culling
  78348. engine.setState(material.backFaceCulling);
  78349. // Managing instances
  78350. var batch = mesh._getInstancesRenderList(subMesh._id);
  78351. if (batch.mustReturn) {
  78352. return;
  78353. }
  78354. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78355. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78356. var effect = _this._volumetricLightScatteringPass;
  78357. if (mesh === _this.mesh) {
  78358. if (subMesh.effect) {
  78359. effect = subMesh.effect;
  78360. }
  78361. else {
  78362. effect = material.getEffect();
  78363. }
  78364. }
  78365. engine.enableEffect(effect);
  78366. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78367. if (mesh === _this.mesh) {
  78368. material.bind(mesh.getWorldMatrix(), mesh);
  78369. }
  78370. else {
  78371. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78372. // Alpha test
  78373. if (material && material.needAlphaTesting()) {
  78374. var alphaTexture = material.getAlphaTestTexture();
  78375. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78376. if (alphaTexture) {
  78377. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78378. }
  78379. }
  78380. // Bones
  78381. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78382. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78383. }
  78384. }
  78385. // Draw
  78386. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78387. }
  78388. };
  78389. // Render target texture callbacks
  78390. var savedSceneClearColor;
  78391. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78392. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78393. savedSceneClearColor = scene.clearColor;
  78394. scene.clearColor = sceneClearColor;
  78395. });
  78396. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78397. scene.clearColor = savedSceneClearColor;
  78398. });
  78399. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78400. var engine = scene.getEngine();
  78401. var index;
  78402. if (depthOnlySubMeshes.length) {
  78403. engine.setColorWrite(false);
  78404. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78405. renderSubMesh(depthOnlySubMeshes.data[index]);
  78406. }
  78407. engine.setColorWrite(true);
  78408. }
  78409. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78410. renderSubMesh(opaqueSubMeshes.data[index]);
  78411. }
  78412. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78413. renderSubMesh(alphaTestSubMeshes.data[index]);
  78414. }
  78415. if (transparentSubMeshes.length) {
  78416. // Sort sub meshes
  78417. for (index = 0; index < transparentSubMeshes.length; index++) {
  78418. var submesh = transparentSubMeshes.data[index];
  78419. var boundingInfo = submesh.getBoundingInfo();
  78420. if (boundingInfo && scene.activeCamera) {
  78421. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78422. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78423. }
  78424. }
  78425. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78426. sortedArray.sort(function (a, b) {
  78427. // Alpha index first
  78428. if (a._alphaIndex > b._alphaIndex) {
  78429. return 1;
  78430. }
  78431. if (a._alphaIndex < b._alphaIndex) {
  78432. return -1;
  78433. }
  78434. // Then distance to camera
  78435. if (a._distanceToCamera < b._distanceToCamera) {
  78436. return 1;
  78437. }
  78438. if (a._distanceToCamera > b._distanceToCamera) {
  78439. return -1;
  78440. }
  78441. return 0;
  78442. });
  78443. // Render sub meshes
  78444. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78445. for (index = 0; index < sortedArray.length; index++) {
  78446. renderSubMesh(sortedArray[index]);
  78447. }
  78448. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78449. }
  78450. };
  78451. };
  78452. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78453. var transform = scene.getTransformMatrix();
  78454. var meshPosition;
  78455. if (this.useCustomMeshPosition) {
  78456. meshPosition = this.customMeshPosition;
  78457. }
  78458. else if (this.attachedNode) {
  78459. meshPosition = this.attachedNode.position;
  78460. }
  78461. else {
  78462. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78463. }
  78464. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78465. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78466. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78467. if (this.invert)
  78468. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78469. };
  78470. // Static methods
  78471. /**
  78472. * Creates a default mesh for the Volumeric Light Scattering post-process
  78473. * @param {string} The mesh name
  78474. * @param {BABYLON.Scene} The scene where to create the mesh
  78475. * @return {BABYLON.Mesh} the default mesh
  78476. */
  78477. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78478. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78479. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78480. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78481. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78482. mesh.material = material;
  78483. return mesh;
  78484. };
  78485. __decorate([
  78486. BABYLON.serializeAsVector3()
  78487. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78488. __decorate([
  78489. BABYLON.serialize()
  78490. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78491. __decorate([
  78492. BABYLON.serialize()
  78493. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78494. __decorate([
  78495. BABYLON.serializeAsMeshReference()
  78496. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78497. __decorate([
  78498. BABYLON.serialize()
  78499. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78500. __decorate([
  78501. BABYLON.serialize()
  78502. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78503. __decorate([
  78504. BABYLON.serialize()
  78505. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78506. __decorate([
  78507. BABYLON.serialize()
  78508. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78509. __decorate([
  78510. BABYLON.serialize()
  78511. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78512. return VolumetricLightScatteringPostProcess;
  78513. }(BABYLON.PostProcess));
  78514. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78515. })(BABYLON || (BABYLON = {}));
  78516. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78517. //
  78518. // This post-process allows the modification of rendered colors by using
  78519. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78520. //
  78521. // The object needs to be provided an url to a texture containing the color
  78522. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78523. // Use an image editing software to tweak the LUT to match your needs.
  78524. //
  78525. // For an example of a color LUT, see here:
  78526. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78527. // For explanations on color grading, see here:
  78528. // http://udn.epicgames.com/Three/ColorGrading.html
  78529. //
  78530. var BABYLON;
  78531. (function (BABYLON) {
  78532. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78533. __extends(ColorCorrectionPostProcess, _super);
  78534. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78535. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78536. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78537. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78538. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78539. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78540. _this.onApply = function (effect) {
  78541. effect.setTexture("colorTable", _this._colorTableTexture);
  78542. };
  78543. return _this;
  78544. }
  78545. return ColorCorrectionPostProcess;
  78546. }(BABYLON.PostProcess));
  78547. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78548. })(BABYLON || (BABYLON = {}));
  78549. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78550. var BABYLON;
  78551. (function (BABYLON) {
  78552. /** Defines operator used for tonemapping */
  78553. var TonemappingOperator;
  78554. (function (TonemappingOperator) {
  78555. /** Hable */
  78556. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78557. /** Reinhard */
  78558. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78559. /** HejiDawson */
  78560. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78561. /** Photographic */
  78562. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78563. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78564. ;
  78565. /**
  78566. * Defines a post process to apply tone mapping
  78567. */
  78568. var TonemapPostProcess = /** @class */ (function (_super) {
  78569. __extends(TonemapPostProcess, _super);
  78570. /**
  78571. * Creates a new TonemapPostProcess
  78572. * @param name defines the name of the postprocess
  78573. * @param _operator defines the operator to use
  78574. * @param exposureAdjustment defines the required exposure adjustement
  78575. * @param camera defines the camera to use (can be null)
  78576. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78577. * @param engine defines the hosting engine (can be ignore if camera is set)
  78578. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78579. */
  78580. function TonemapPostProcess(name, _operator,
  78581. /** Defines the required exposure adjustement */
  78582. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78584. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78585. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78586. _this._operator = _operator;
  78587. _this.exposureAdjustment = exposureAdjustment;
  78588. var defines = "#define ";
  78589. if (_this._operator === TonemappingOperator.Hable)
  78590. defines += "HABLE_TONEMAPPING";
  78591. else if (_this._operator === TonemappingOperator.Reinhard)
  78592. defines += "REINHARD_TONEMAPPING";
  78593. else if (_this._operator === TonemappingOperator.HejiDawson)
  78594. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78595. else if (_this._operator === TonemappingOperator.Photographic)
  78596. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78597. //sadly a second call to create the effect.
  78598. _this.updateEffect(defines);
  78599. _this.onApply = function (effect) {
  78600. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78601. };
  78602. return _this;
  78603. }
  78604. return TonemapPostProcess;
  78605. }(BABYLON.PostProcess));
  78606. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78607. })(BABYLON || (BABYLON = {}));
  78608. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78609. var BABYLON;
  78610. (function (BABYLON) {
  78611. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78612. __extends(DisplayPassPostProcess, _super);
  78613. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78614. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78615. }
  78616. return DisplayPassPostProcess;
  78617. }(BABYLON.PostProcess));
  78618. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78619. })(BABYLON || (BABYLON = {}));
  78620. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78621. var BABYLON;
  78622. (function (BABYLON) {
  78623. var HighlightsPostProcess = /** @class */ (function (_super) {
  78624. __extends(HighlightsPostProcess, _super);
  78625. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78626. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78627. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78628. }
  78629. return HighlightsPostProcess;
  78630. }(BABYLON.PostProcess));
  78631. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78632. })(BABYLON || (BABYLON = {}));
  78633. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78634. var BABYLON;
  78635. (function (BABYLON) {
  78636. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78637. __extends(ImageProcessingPostProcess, _super);
  78638. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78639. if (camera === void 0) { camera = null; }
  78640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78641. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78642. _this._fromLinearSpace = true;
  78643. /**
  78644. * Defines cache preventing GC.
  78645. */
  78646. _this._defines = {
  78647. IMAGEPROCESSING: false,
  78648. VIGNETTE: false,
  78649. VIGNETTEBLENDMODEMULTIPLY: false,
  78650. VIGNETTEBLENDMODEOPAQUE: false,
  78651. TONEMAPPING: false,
  78652. CONTRAST: false,
  78653. COLORCURVES: false,
  78654. COLORGRADING: false,
  78655. COLORGRADING3D: false,
  78656. FROMLINEARSPACE: false,
  78657. SAMPLER3DGREENDEPTH: false,
  78658. SAMPLER3DBGRMAP: false,
  78659. IMAGEPROCESSINGPOSTPROCESS: false,
  78660. EXPOSURE: false,
  78661. };
  78662. // Setup the configuration as forced by the constructor. This would then not force the
  78663. // scene materials output in linear space and let untouched the default forward pass.
  78664. if (imageProcessingConfiguration) {
  78665. imageProcessingConfiguration.applyByPostProcess = true;
  78666. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78667. // This will cause the shader to be compiled
  78668. _this.fromLinearSpace = false;
  78669. }
  78670. // Setup the default processing configuration to the scene.
  78671. else {
  78672. _this._attachImageProcessingConfiguration(null, true);
  78673. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78674. }
  78675. _this.onApply = function (effect) {
  78676. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78677. };
  78678. return _this;
  78679. }
  78680. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78681. /**
  78682. * Gets the image processing configuration used either in this material.
  78683. */
  78684. get: function () {
  78685. return this._imageProcessingConfiguration;
  78686. },
  78687. /**
  78688. * Sets the Default image processing configuration used either in the this material.
  78689. *
  78690. * If sets to null, the scene one is in use.
  78691. */
  78692. set: function (value) {
  78693. this._attachImageProcessingConfiguration(value);
  78694. },
  78695. enumerable: true,
  78696. configurable: true
  78697. });
  78698. /**
  78699. * Attaches a new image processing configuration to the PBR Material.
  78700. * @param configuration
  78701. */
  78702. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78703. var _this = this;
  78704. if (doNotBuild === void 0) { doNotBuild = false; }
  78705. if (configuration === this._imageProcessingConfiguration) {
  78706. return;
  78707. }
  78708. // Detaches observer.
  78709. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78710. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78711. }
  78712. // Pick the scene configuration if needed.
  78713. if (!configuration) {
  78714. var scene = null;
  78715. var engine = this.getEngine();
  78716. var camera = this.getCamera();
  78717. if (camera) {
  78718. scene = camera.getScene();
  78719. }
  78720. else if (engine && engine.scenes) {
  78721. var scenes = engine.scenes;
  78722. scene = scenes[scenes.length - 1];
  78723. }
  78724. else {
  78725. scene = BABYLON.Engine.LastCreatedScene;
  78726. }
  78727. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78728. }
  78729. else {
  78730. this._imageProcessingConfiguration = configuration;
  78731. }
  78732. // Attaches observer.
  78733. if (this._imageProcessingConfiguration) {
  78734. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78735. _this._updateParameters();
  78736. });
  78737. }
  78738. // Ensure the effect will be rebuilt.
  78739. if (!doNotBuild) {
  78740. this._updateParameters();
  78741. }
  78742. };
  78743. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78744. /**
  78745. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78746. */
  78747. get: function () {
  78748. return this.imageProcessingConfiguration.colorCurves;
  78749. },
  78750. /**
  78751. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78752. */
  78753. set: function (value) {
  78754. this.imageProcessingConfiguration.colorCurves = value;
  78755. },
  78756. enumerable: true,
  78757. configurable: true
  78758. });
  78759. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78760. /**
  78761. * Gets wether the color curves effect is enabled.
  78762. */
  78763. get: function () {
  78764. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78765. },
  78766. /**
  78767. * Sets wether the color curves effect is enabled.
  78768. */
  78769. set: function (value) {
  78770. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78771. },
  78772. enumerable: true,
  78773. configurable: true
  78774. });
  78775. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78776. /**
  78777. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78778. */
  78779. get: function () {
  78780. return this.imageProcessingConfiguration.colorGradingTexture;
  78781. },
  78782. /**
  78783. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78784. */
  78785. set: function (value) {
  78786. this.imageProcessingConfiguration.colorGradingTexture = value;
  78787. },
  78788. enumerable: true,
  78789. configurable: true
  78790. });
  78791. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78792. /**
  78793. * Gets wether the color grading effect is enabled.
  78794. */
  78795. get: function () {
  78796. return this.imageProcessingConfiguration.colorGradingEnabled;
  78797. },
  78798. /**
  78799. * Gets wether the color grading effect is enabled.
  78800. */
  78801. set: function (value) {
  78802. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78803. },
  78804. enumerable: true,
  78805. configurable: true
  78806. });
  78807. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78808. /**
  78809. * Gets exposure used in the effect.
  78810. */
  78811. get: function () {
  78812. return this.imageProcessingConfiguration.exposure;
  78813. },
  78814. /**
  78815. * Sets exposure used in the effect.
  78816. */
  78817. set: function (value) {
  78818. this.imageProcessingConfiguration.exposure = value;
  78819. },
  78820. enumerable: true,
  78821. configurable: true
  78822. });
  78823. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78824. /**
  78825. * Gets wether tonemapping is enabled or not.
  78826. */
  78827. get: function () {
  78828. return this._imageProcessingConfiguration.toneMappingEnabled;
  78829. },
  78830. /**
  78831. * Sets wether tonemapping is enabled or not
  78832. */
  78833. set: function (value) {
  78834. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78835. },
  78836. enumerable: true,
  78837. configurable: true
  78838. });
  78839. ;
  78840. ;
  78841. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78842. /**
  78843. * Gets contrast used in the effect.
  78844. */
  78845. get: function () {
  78846. return this.imageProcessingConfiguration.contrast;
  78847. },
  78848. /**
  78849. * Sets contrast used in the effect.
  78850. */
  78851. set: function (value) {
  78852. this.imageProcessingConfiguration.contrast = value;
  78853. },
  78854. enumerable: true,
  78855. configurable: true
  78856. });
  78857. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78858. /**
  78859. * Gets Vignette stretch size.
  78860. */
  78861. get: function () {
  78862. return this.imageProcessingConfiguration.vignetteStretch;
  78863. },
  78864. /**
  78865. * Sets Vignette stretch size.
  78866. */
  78867. set: function (value) {
  78868. this.imageProcessingConfiguration.vignetteStretch = value;
  78869. },
  78870. enumerable: true,
  78871. configurable: true
  78872. });
  78873. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78874. /**
  78875. * Gets Vignette centre X Offset.
  78876. */
  78877. get: function () {
  78878. return this.imageProcessingConfiguration.vignetteCentreX;
  78879. },
  78880. /**
  78881. * Sets Vignette centre X Offset.
  78882. */
  78883. set: function (value) {
  78884. this.imageProcessingConfiguration.vignetteCentreX = value;
  78885. },
  78886. enumerable: true,
  78887. configurable: true
  78888. });
  78889. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78890. /**
  78891. * Gets Vignette centre Y Offset.
  78892. */
  78893. get: function () {
  78894. return this.imageProcessingConfiguration.vignetteCentreY;
  78895. },
  78896. /**
  78897. * Sets Vignette centre Y Offset.
  78898. */
  78899. set: function (value) {
  78900. this.imageProcessingConfiguration.vignetteCentreY = value;
  78901. },
  78902. enumerable: true,
  78903. configurable: true
  78904. });
  78905. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78906. /**
  78907. * Gets Vignette weight or intensity of the vignette effect.
  78908. */
  78909. get: function () {
  78910. return this.imageProcessingConfiguration.vignetteWeight;
  78911. },
  78912. /**
  78913. * Sets Vignette weight or intensity of the vignette effect.
  78914. */
  78915. set: function (value) {
  78916. this.imageProcessingConfiguration.vignetteWeight = value;
  78917. },
  78918. enumerable: true,
  78919. configurable: true
  78920. });
  78921. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78922. /**
  78923. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78924. * if vignetteEnabled is set to true.
  78925. */
  78926. get: function () {
  78927. return this.imageProcessingConfiguration.vignetteColor;
  78928. },
  78929. /**
  78930. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78931. * if vignetteEnabled is set to true.
  78932. */
  78933. set: function (value) {
  78934. this.imageProcessingConfiguration.vignetteColor = value;
  78935. },
  78936. enumerable: true,
  78937. configurable: true
  78938. });
  78939. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78940. /**
  78941. * Gets Camera field of view used by the Vignette effect.
  78942. */
  78943. get: function () {
  78944. return this.imageProcessingConfiguration.vignetteCameraFov;
  78945. },
  78946. /**
  78947. * Sets Camera field of view used by the Vignette effect.
  78948. */
  78949. set: function (value) {
  78950. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78951. },
  78952. enumerable: true,
  78953. configurable: true
  78954. });
  78955. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78956. /**
  78957. * Gets the vignette blend mode allowing different kind of effect.
  78958. */
  78959. get: function () {
  78960. return this.imageProcessingConfiguration.vignetteBlendMode;
  78961. },
  78962. /**
  78963. * Sets the vignette blend mode allowing different kind of effect.
  78964. */
  78965. set: function (value) {
  78966. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78967. },
  78968. enumerable: true,
  78969. configurable: true
  78970. });
  78971. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78972. /**
  78973. * Gets wether the vignette effect is enabled.
  78974. */
  78975. get: function () {
  78976. return this.imageProcessingConfiguration.vignetteEnabled;
  78977. },
  78978. /**
  78979. * Sets wether the vignette effect is enabled.
  78980. */
  78981. set: function (value) {
  78982. this.imageProcessingConfiguration.vignetteEnabled = value;
  78983. },
  78984. enumerable: true,
  78985. configurable: true
  78986. });
  78987. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78988. /**
  78989. * Gets wether the input of the processing is in Gamma or Linear Space.
  78990. */
  78991. get: function () {
  78992. return this._fromLinearSpace;
  78993. },
  78994. /**
  78995. * Sets wether the input of the processing is in Gamma or Linear Space.
  78996. */
  78997. set: function (value) {
  78998. if (this._fromLinearSpace === value) {
  78999. return;
  79000. }
  79001. this._fromLinearSpace = value;
  79002. this._updateParameters();
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. ImageProcessingPostProcess.prototype.getClassName = function () {
  79008. return "ImageProcessingPostProcess";
  79009. };
  79010. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79011. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79012. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79013. var defines = "";
  79014. for (var define in this._defines) {
  79015. if (this._defines[define]) {
  79016. defines += "#define " + define + ";\r\n";
  79017. }
  79018. }
  79019. var samplers = ["textureSampler"];
  79020. var uniforms = ["scale"];
  79021. if (BABYLON.ImageProcessingConfiguration) {
  79022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79023. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79024. }
  79025. this.updateEffect(defines, uniforms, samplers);
  79026. };
  79027. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79028. _super.prototype.dispose.call(this, camera);
  79029. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79030. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79031. }
  79032. if (this._imageProcessingConfiguration) {
  79033. this.imageProcessingConfiguration.applyByPostProcess = false;
  79034. }
  79035. };
  79036. __decorate([
  79037. BABYLON.serialize()
  79038. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79039. return ImageProcessingPostProcess;
  79040. }(BABYLON.PostProcess));
  79041. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79042. })(BABYLON || (BABYLON = {}));
  79043. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79044. var BABYLON;
  79045. (function (BABYLON) {
  79046. /**
  79047. * Class used to store bone information
  79048. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79049. */
  79050. var Bone = /** @class */ (function (_super) {
  79051. __extends(Bone, _super);
  79052. /**
  79053. * Create a new bone
  79054. * @param name defines the bone name
  79055. * @param skeleton defines the parent skeleton
  79056. * @param parentBone defines the parent (can be null if the bone is the root)
  79057. * @param localMatrix defines the local matrix
  79058. * @param restPose defines the rest pose matrix
  79059. * @param baseMatrix defines the base matrix
  79060. * @param index defines index of the bone in the hiearchy
  79061. */
  79062. function Bone(
  79063. /**
  79064. * defines the bone name
  79065. */
  79066. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79067. if (parentBone === void 0) { parentBone = null; }
  79068. if (localMatrix === void 0) { localMatrix = null; }
  79069. if (restPose === void 0) { restPose = null; }
  79070. if (baseMatrix === void 0) { baseMatrix = null; }
  79071. if (index === void 0) { index = null; }
  79072. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79073. _this.name = name;
  79074. /**
  79075. * Gets the list of child bones
  79076. */
  79077. _this.children = new Array();
  79078. /** Gets the animations associated with this bone */
  79079. _this.animations = new Array();
  79080. /**
  79081. * @hidden Internal only
  79082. * Set this value to map this bone to a different index in the transform matrices
  79083. * Set this value to -1 to exclude the bone from the transform matrices
  79084. */
  79085. _this._index = null;
  79086. _this._absoluteTransform = new BABYLON.Matrix();
  79087. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79088. _this._scalingDeterminant = 1;
  79089. _this._worldTransform = new BABYLON.Matrix();
  79090. _this._needToDecompose = true;
  79091. _this._needToCompose = false;
  79092. _this._skeleton = skeleton;
  79093. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79094. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79095. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79096. _this._index = index;
  79097. skeleton.bones.push(_this);
  79098. _this.setParent(parentBone, false);
  79099. if (baseMatrix || localMatrix) {
  79100. _this._updateDifferenceMatrix();
  79101. }
  79102. return _this;
  79103. }
  79104. Object.defineProperty(Bone.prototype, "_matrix", {
  79105. /** @hidden */
  79106. get: function () {
  79107. this._compose();
  79108. return this._localMatrix;
  79109. },
  79110. /** @hidden */
  79111. set: function (value) {
  79112. this._localMatrix.copyFrom(value);
  79113. this._needToDecompose = true;
  79114. },
  79115. enumerable: true,
  79116. configurable: true
  79117. });
  79118. // Members
  79119. /**
  79120. * Gets the parent skeleton
  79121. * @returns a skeleton
  79122. */
  79123. Bone.prototype.getSkeleton = function () {
  79124. return this._skeleton;
  79125. };
  79126. /**
  79127. * Gets parent bone
  79128. * @returns a bone or null if the bone is the root of the bone hierarchy
  79129. */
  79130. Bone.prototype.getParent = function () {
  79131. return this._parent;
  79132. };
  79133. /**
  79134. * Sets the parent bone
  79135. * @param parent defines the parent (can be null if the bone is the root)
  79136. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79137. */
  79138. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79139. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79140. if (this._parent === parent) {
  79141. return;
  79142. }
  79143. if (this._parent) {
  79144. var index = this._parent.children.indexOf(this);
  79145. if (index !== -1) {
  79146. this._parent.children.splice(index, 1);
  79147. }
  79148. }
  79149. this._parent = parent;
  79150. if (this._parent) {
  79151. this._parent.children.push(this);
  79152. }
  79153. if (updateDifferenceMatrix) {
  79154. this._updateDifferenceMatrix();
  79155. }
  79156. this.markAsDirty();
  79157. };
  79158. /**
  79159. * Gets the local matrix
  79160. * @returns a matrix
  79161. */
  79162. Bone.prototype.getLocalMatrix = function () {
  79163. this._compose();
  79164. return this._localMatrix;
  79165. };
  79166. /**
  79167. * Gets the base matrix (initial matrix which remains unchanged)
  79168. * @returns a matrix
  79169. */
  79170. Bone.prototype.getBaseMatrix = function () {
  79171. return this._baseMatrix;
  79172. };
  79173. /**
  79174. * Gets the rest pose matrix
  79175. * @returns a matrix
  79176. */
  79177. Bone.prototype.getRestPose = function () {
  79178. return this._restPose;
  79179. };
  79180. /**
  79181. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79182. */
  79183. Bone.prototype.getWorldMatrix = function () {
  79184. return this._worldTransform;
  79185. };
  79186. /**
  79187. * Sets the local matrix to rest pose matrix
  79188. */
  79189. Bone.prototype.returnToRest = function () {
  79190. this.updateMatrix(this._restPose.clone());
  79191. };
  79192. /**
  79193. * Gets the inverse of the absolute transform matrix.
  79194. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79195. * @returns a matrix
  79196. */
  79197. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79198. return this._invertedAbsoluteTransform;
  79199. };
  79200. /**
  79201. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79202. * @returns a matrix
  79203. */
  79204. Bone.prototype.getAbsoluteTransform = function () {
  79205. return this._absoluteTransform;
  79206. };
  79207. Object.defineProperty(Bone.prototype, "position", {
  79208. // Properties (matches AbstractMesh properties)
  79209. /** Gets or sets current position (in local space) */
  79210. get: function () {
  79211. this._decompose();
  79212. return this._localPosition;
  79213. },
  79214. set: function (newPosition) {
  79215. this._decompose();
  79216. this._localPosition.copyFrom(newPosition);
  79217. this._markAsDirtyAndCompose();
  79218. },
  79219. enumerable: true,
  79220. configurable: true
  79221. });
  79222. Object.defineProperty(Bone.prototype, "rotation", {
  79223. /** Gets or sets current rotation (in local space) */
  79224. get: function () {
  79225. return this.getRotation();
  79226. },
  79227. set: function (newRotation) {
  79228. this.setRotation(newRotation);
  79229. },
  79230. enumerable: true,
  79231. configurable: true
  79232. });
  79233. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79234. /** Gets or sets current rotation quaternion (in local space) */
  79235. get: function () {
  79236. this._decompose();
  79237. return this._localRotation;
  79238. },
  79239. set: function (newRotation) {
  79240. this.setRotationQuaternion(newRotation);
  79241. },
  79242. enumerable: true,
  79243. configurable: true
  79244. });
  79245. Object.defineProperty(Bone.prototype, "scaling", {
  79246. /** Gets or sets current scaling (in local space) */
  79247. get: function () {
  79248. return this.getScale();
  79249. },
  79250. set: function (newScaling) {
  79251. this.setScale(newScaling);
  79252. },
  79253. enumerable: true,
  79254. configurable: true
  79255. });
  79256. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79257. /**
  79258. * Gets the animation properties override
  79259. */
  79260. get: function () {
  79261. return this._skeleton.animationPropertiesOverride;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. // Methods
  79267. Bone.prototype._decompose = function () {
  79268. if (!this._needToDecompose) {
  79269. return;
  79270. }
  79271. this._needToDecompose = false;
  79272. if (!this._localScaling) {
  79273. this._localScaling = BABYLON.Vector3.Zero();
  79274. this._localRotation = BABYLON.Quaternion.Zero();
  79275. this._localPosition = BABYLON.Vector3.Zero();
  79276. }
  79277. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79278. };
  79279. Bone.prototype._compose = function () {
  79280. if (!this._needToCompose) {
  79281. return;
  79282. }
  79283. this._needToCompose = false;
  79284. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79285. };
  79286. /**
  79287. * Update the base and local matrices
  79288. * @param matrix defines the new base or local matrix
  79289. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79290. * @param updateLocalMatrix defines if the local matrix should be updated
  79291. */
  79292. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79293. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79294. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79295. this._baseMatrix.copyFrom(matrix);
  79296. if (updateDifferenceMatrix) {
  79297. this._updateDifferenceMatrix();
  79298. }
  79299. if (updateLocalMatrix) {
  79300. this._localMatrix.copyFrom(matrix);
  79301. this._markAsDirtyAndDecompose();
  79302. }
  79303. else {
  79304. this.markAsDirty();
  79305. }
  79306. };
  79307. /** @hidden */
  79308. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79309. if (updateChildren === void 0) { updateChildren = true; }
  79310. if (!rootMatrix) {
  79311. rootMatrix = this._baseMatrix;
  79312. }
  79313. if (this._parent) {
  79314. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79315. }
  79316. else {
  79317. this._absoluteTransform.copyFrom(rootMatrix);
  79318. }
  79319. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79320. if (updateChildren) {
  79321. for (var index = 0; index < this.children.length; index++) {
  79322. this.children[index]._updateDifferenceMatrix();
  79323. }
  79324. }
  79325. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79326. };
  79327. /**
  79328. * Flag the bone as dirty (Forcing it to update everything)
  79329. */
  79330. Bone.prototype.markAsDirty = function () {
  79331. this._currentRenderId++;
  79332. this._childRenderId++;
  79333. this._skeleton._markAsDirty();
  79334. };
  79335. Bone.prototype._markAsDirtyAndCompose = function () {
  79336. this.markAsDirty();
  79337. this._needToCompose = true;
  79338. };
  79339. Bone.prototype._markAsDirtyAndDecompose = function () {
  79340. this.markAsDirty();
  79341. this._needToDecompose = true;
  79342. };
  79343. /**
  79344. * Copy an animation range from another bone
  79345. * @param source defines the source bone
  79346. * @param rangeName defines the range name to copy
  79347. * @param frameOffset defines the frame offset
  79348. * @param rescaleAsRequired defines if rescaling must be applied if required
  79349. * @param skelDimensionsRatio defines the scaling ratio
  79350. * @returns true if operation was successful
  79351. */
  79352. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79353. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79354. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79355. // all animation may be coming from a library skeleton, so may need to create animation
  79356. if (this.animations.length === 0) {
  79357. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79358. this.animations[0].setKeys([]);
  79359. }
  79360. // get animation info / verify there is such a range from the source bone
  79361. var sourceRange = source.animations[0].getRange(rangeName);
  79362. if (!sourceRange) {
  79363. return false;
  79364. }
  79365. var from = sourceRange.from;
  79366. var to = sourceRange.to;
  79367. var sourceKeys = source.animations[0].getKeys();
  79368. // rescaling prep
  79369. var sourceBoneLength = source.length;
  79370. var sourceParent = source.getParent();
  79371. var parent = this.getParent();
  79372. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79373. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79374. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79375. var destKeys = this.animations[0].getKeys();
  79376. // loop vars declaration
  79377. var orig;
  79378. var origTranslation;
  79379. var mat;
  79380. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79381. orig = sourceKeys[key];
  79382. if (orig.frame >= from && orig.frame <= to) {
  79383. if (rescaleAsRequired) {
  79384. mat = orig.value.clone();
  79385. // scale based on parent ratio, when bone has parent
  79386. if (parentScalingReqd) {
  79387. origTranslation = mat.getTranslation();
  79388. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79389. // scale based on skeleton dimension ratio when root bone, and value is passed
  79390. }
  79391. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79392. origTranslation = mat.getTranslation();
  79393. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79394. // use original when root bone, and no data for skelDimensionsRatio
  79395. }
  79396. else {
  79397. mat = orig.value;
  79398. }
  79399. }
  79400. else {
  79401. mat = orig.value;
  79402. }
  79403. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79404. }
  79405. }
  79406. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79407. return true;
  79408. };
  79409. /**
  79410. * Translate the bone in local or world space
  79411. * @param vec The amount to translate the bone
  79412. * @param space The space that the translation is in
  79413. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79414. */
  79415. Bone.prototype.translate = function (vec, space, mesh) {
  79416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79417. var lm = this.getLocalMatrix();
  79418. if (space == BABYLON.Space.LOCAL) {
  79419. lm.m[12] += vec.x;
  79420. lm.m[13] += vec.y;
  79421. lm.m[14] += vec.z;
  79422. }
  79423. else {
  79424. var wm = null;
  79425. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79426. if (mesh) {
  79427. wm = mesh.getWorldMatrix();
  79428. }
  79429. this._skeleton.computeAbsoluteTransforms();
  79430. var tmat = Bone._tmpMats[0];
  79431. var tvec = Bone._tmpVecs[0];
  79432. if (this._parent) {
  79433. if (mesh && wm) {
  79434. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79435. tmat.multiplyToRef(wm, tmat);
  79436. }
  79437. else {
  79438. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79439. }
  79440. }
  79441. tmat.m[12] = 0;
  79442. tmat.m[13] = 0;
  79443. tmat.m[14] = 0;
  79444. tmat.invert();
  79445. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79446. lm.m[12] += tvec.x;
  79447. lm.m[13] += tvec.y;
  79448. lm.m[14] += tvec.z;
  79449. }
  79450. this._markAsDirtyAndDecompose();
  79451. };
  79452. /**
  79453. * Set the postion of the bone in local or world space
  79454. * @param position The position to set the bone
  79455. * @param space The space that the position is in
  79456. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79457. */
  79458. Bone.prototype.setPosition = function (position, space, mesh) {
  79459. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79460. var lm = this.getLocalMatrix();
  79461. if (space == BABYLON.Space.LOCAL) {
  79462. lm.m[12] = position.x;
  79463. lm.m[13] = position.y;
  79464. lm.m[14] = position.z;
  79465. }
  79466. else {
  79467. var wm = null;
  79468. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79469. if (mesh) {
  79470. wm = mesh.getWorldMatrix();
  79471. }
  79472. this._skeleton.computeAbsoluteTransforms();
  79473. var tmat = Bone._tmpMats[0];
  79474. var vec = Bone._tmpVecs[0];
  79475. if (this._parent) {
  79476. if (mesh && wm) {
  79477. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79478. tmat.multiplyToRef(wm, tmat);
  79479. }
  79480. else {
  79481. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79482. }
  79483. }
  79484. tmat.invert();
  79485. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79486. lm.m[12] = vec.x;
  79487. lm.m[13] = vec.y;
  79488. lm.m[14] = vec.z;
  79489. }
  79490. this._markAsDirtyAndDecompose();
  79491. };
  79492. /**
  79493. * Set the absolute position of the bone (world space)
  79494. * @param position The position to set the bone
  79495. * @param mesh The mesh that this bone is attached to
  79496. */
  79497. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79498. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79499. };
  79500. /**
  79501. * Scale the bone on the x, y and z axes (in local space)
  79502. * @param x The amount to scale the bone on the x axis
  79503. * @param y The amount to scale the bone on the y axis
  79504. * @param z The amount to scale the bone on the z axis
  79505. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79506. */
  79507. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79508. if (scaleChildren === void 0) { scaleChildren = false; }
  79509. var locMat = this.getLocalMatrix();
  79510. // Apply new scaling on top of current local matrix
  79511. var scaleMat = Bone._tmpMats[0];
  79512. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79513. scaleMat.multiplyToRef(locMat, locMat);
  79514. // Invert scaling matrix and apply the inverse to all children
  79515. scaleMat.invert();
  79516. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79517. var child = _a[_i];
  79518. var cm = child.getLocalMatrix();
  79519. cm.multiplyToRef(scaleMat, cm);
  79520. cm.m[12] *= x;
  79521. cm.m[13] *= y;
  79522. cm.m[14] *= z;
  79523. child._markAsDirtyAndDecompose();
  79524. }
  79525. this._markAsDirtyAndDecompose();
  79526. if (scaleChildren) {
  79527. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79528. var child = _c[_b];
  79529. child.scale(x, y, z, scaleChildren);
  79530. }
  79531. }
  79532. };
  79533. /**
  79534. * Set the bone scaling in local space
  79535. * @param scale defines the scaling vector
  79536. */
  79537. Bone.prototype.setScale = function (scale) {
  79538. this._decompose();
  79539. this._localScaling.copyFrom(scale);
  79540. this._markAsDirtyAndCompose();
  79541. };
  79542. /**
  79543. * Gets the current scaling in local space
  79544. * @returns the current scaling vector
  79545. */
  79546. Bone.prototype.getScale = function () {
  79547. this._decompose();
  79548. return this._localScaling;
  79549. };
  79550. /**
  79551. * Gets the current scaling in local space and stores it in a target vector
  79552. * @param result defines the target vector
  79553. */
  79554. Bone.prototype.getScaleToRef = function (result) {
  79555. this._decompose();
  79556. result.copyFrom(this._localScaling);
  79557. };
  79558. /**
  79559. * Set the yaw, pitch, and roll of the bone in local or world space
  79560. * @param yaw The rotation of the bone on the y axis
  79561. * @param pitch The rotation of the bone on the x axis
  79562. * @param roll The rotation of the bone on the z axis
  79563. * @param space The space that the axes of rotation are in
  79564. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79565. */
  79566. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79568. if (space === BABYLON.Space.LOCAL) {
  79569. var quat = Bone._tmpQuat;
  79570. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79571. this.setRotationQuaternion(quat, space, mesh);
  79572. return;
  79573. }
  79574. var rotMatInv = Bone._tmpMats[0];
  79575. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79576. return;
  79577. }
  79578. var rotMat = Bone._tmpMats[1];
  79579. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79580. rotMatInv.multiplyToRef(rotMat, rotMat);
  79581. this._rotateWithMatrix(rotMat, space, mesh);
  79582. };
  79583. /**
  79584. * Add a rotation to the bone on an axis in local or world space
  79585. * @param axis The axis to rotate the bone on
  79586. * @param amount The amount to rotate the bone
  79587. * @param space The space that the axis is in
  79588. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79589. */
  79590. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79592. var rmat = Bone._tmpMats[0];
  79593. rmat.m[12] = 0;
  79594. rmat.m[13] = 0;
  79595. rmat.m[14] = 0;
  79596. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79597. this._rotateWithMatrix(rmat, space, mesh);
  79598. };
  79599. /**
  79600. * Set the rotation of the bone to a particular axis angle in local or world space
  79601. * @param axis The axis to rotate the bone on
  79602. * @param angle The angle that the bone should be rotated to
  79603. * @param space The space that the axis is in
  79604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79605. */
  79606. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79608. if (space === BABYLON.Space.LOCAL) {
  79609. var quat = Bone._tmpQuat;
  79610. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79611. this.setRotationQuaternion(quat, space, mesh);
  79612. return;
  79613. }
  79614. var rotMatInv = Bone._tmpMats[0];
  79615. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79616. return;
  79617. }
  79618. var rotMat = Bone._tmpMats[1];
  79619. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79620. rotMatInv.multiplyToRef(rotMat, rotMat);
  79621. this._rotateWithMatrix(rotMat, space, mesh);
  79622. };
  79623. /**
  79624. * Set the euler rotation of the bone in local of world space
  79625. * @param rotation The euler rotation that the bone should be set to
  79626. * @param space The space that the rotation is in
  79627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79628. */
  79629. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79631. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79632. };
  79633. /**
  79634. * Set the quaternion rotation of the bone in local of world space
  79635. * @param quat The quaternion rotation that the bone should be set to
  79636. * @param space The space that the rotation is in
  79637. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79638. */
  79639. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79641. if (space === BABYLON.Space.LOCAL) {
  79642. this._decompose();
  79643. this._localRotation.copyFrom(quat);
  79644. this._markAsDirtyAndCompose();
  79645. return;
  79646. }
  79647. var rotMatInv = Bone._tmpMats[0];
  79648. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79649. return;
  79650. }
  79651. var rotMat = Bone._tmpMats[1];
  79652. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79653. rotMatInv.multiplyToRef(rotMat, rotMat);
  79654. this._rotateWithMatrix(rotMat, space, mesh);
  79655. };
  79656. /**
  79657. * Set the rotation matrix of the bone in local of world space
  79658. * @param rotMat The rotation matrix that the bone should be set to
  79659. * @param space The space that the rotation is in
  79660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79661. */
  79662. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79664. if (space === BABYLON.Space.LOCAL) {
  79665. var quat = Bone._tmpQuat;
  79666. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79667. this.setRotationQuaternion(quat, space, mesh);
  79668. return;
  79669. }
  79670. var rotMatInv = Bone._tmpMats[0];
  79671. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79672. return;
  79673. }
  79674. var rotMat2 = Bone._tmpMats[1];
  79675. rotMat2.copyFrom(rotMat);
  79676. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79677. this._rotateWithMatrix(rotMat2, space, mesh);
  79678. };
  79679. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79681. var lmat = this.getLocalMatrix();
  79682. var lx = lmat.m[12];
  79683. var ly = lmat.m[13];
  79684. var lz = lmat.m[14];
  79685. var parent = this.getParent();
  79686. var parentScale = Bone._tmpMats[3];
  79687. var parentScaleInv = Bone._tmpMats[4];
  79688. if (parent && space == BABYLON.Space.WORLD) {
  79689. if (mesh) {
  79690. parentScale.copyFrom(mesh.getWorldMatrix());
  79691. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79692. }
  79693. else {
  79694. parentScale.copyFrom(parent.getAbsoluteTransform());
  79695. }
  79696. parentScaleInv.copyFrom(parentScale);
  79697. parentScaleInv.invert();
  79698. lmat.multiplyToRef(parentScale, lmat);
  79699. lmat.multiplyToRef(rmat, lmat);
  79700. lmat.multiplyToRef(parentScaleInv, lmat);
  79701. }
  79702. else {
  79703. if (space == BABYLON.Space.WORLD && mesh) {
  79704. parentScale.copyFrom(mesh.getWorldMatrix());
  79705. parentScaleInv.copyFrom(parentScale);
  79706. parentScaleInv.invert();
  79707. lmat.multiplyToRef(parentScale, lmat);
  79708. lmat.multiplyToRef(rmat, lmat);
  79709. lmat.multiplyToRef(parentScaleInv, lmat);
  79710. }
  79711. else {
  79712. lmat.multiplyToRef(rmat, lmat);
  79713. }
  79714. }
  79715. lmat.m[12] = lx;
  79716. lmat.m[13] = ly;
  79717. lmat.m[14] = lz;
  79718. this.computeAbsoluteTransforms();
  79719. this._markAsDirtyAndDecompose();
  79720. };
  79721. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79722. var scaleMatrix = Bone._tmpMats[2];
  79723. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79724. if (mesh) {
  79725. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79726. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79727. }
  79728. rotMatInv.invert();
  79729. if (isNaN(rotMatInv.m[0])) {
  79730. // Matrix failed to invert.
  79731. // This can happen if scale is zero for example.
  79732. return false;
  79733. }
  79734. scaleMatrix.m[0] *= this._scalingDeterminant;
  79735. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79736. return true;
  79737. };
  79738. /**
  79739. * Get the position of the bone in local or world space
  79740. * @param space The space that the returned position is in
  79741. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79742. * @returns The position of the bone
  79743. */
  79744. Bone.prototype.getPosition = function (space, mesh) {
  79745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79746. if (mesh === void 0) { mesh = null; }
  79747. var pos = BABYLON.Vector3.Zero();
  79748. this.getPositionToRef(space, mesh, pos);
  79749. return pos;
  79750. };
  79751. /**
  79752. * Copy the position of the bone to a vector3 in local or world space
  79753. * @param space The space that the returned position is in
  79754. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79755. * @param result The vector3 to copy the position to
  79756. */
  79757. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79759. if (space == BABYLON.Space.LOCAL) {
  79760. var lm = this.getLocalMatrix();
  79761. result.x = lm.m[12];
  79762. result.y = lm.m[13];
  79763. result.z = lm.m[14];
  79764. }
  79765. else {
  79766. var wm = null;
  79767. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79768. if (mesh) {
  79769. wm = mesh.getWorldMatrix();
  79770. }
  79771. this._skeleton.computeAbsoluteTransforms();
  79772. var tmat = Bone._tmpMats[0];
  79773. if (mesh && wm) {
  79774. tmat.copyFrom(this.getAbsoluteTransform());
  79775. tmat.multiplyToRef(wm, tmat);
  79776. }
  79777. else {
  79778. tmat = this.getAbsoluteTransform();
  79779. }
  79780. result.x = tmat.m[12];
  79781. result.y = tmat.m[13];
  79782. result.z = tmat.m[14];
  79783. }
  79784. };
  79785. /**
  79786. * Get the absolute position of the bone (world space)
  79787. * @param mesh The mesh that this bone is attached to
  79788. * @returns The absolute position of the bone
  79789. */
  79790. Bone.prototype.getAbsolutePosition = function (mesh) {
  79791. if (mesh === void 0) { mesh = null; }
  79792. var pos = BABYLON.Vector3.Zero();
  79793. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79794. return pos;
  79795. };
  79796. /**
  79797. * Copy the absolute position of the bone (world space) to the result param
  79798. * @param mesh The mesh that this bone is attached to
  79799. * @param result The vector3 to copy the absolute position to
  79800. */
  79801. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79802. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79803. };
  79804. /**
  79805. * Compute the absolute transforms of this bone and its children
  79806. */
  79807. Bone.prototype.computeAbsoluteTransforms = function () {
  79808. this._compose();
  79809. if (this._parent) {
  79810. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79811. }
  79812. else {
  79813. this._absoluteTransform.copyFrom(this._localMatrix);
  79814. var poseMatrix = this._skeleton.getPoseMatrix();
  79815. if (poseMatrix) {
  79816. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79817. }
  79818. }
  79819. var children = this.children;
  79820. var len = children.length;
  79821. for (var i = 0; i < len; i++) {
  79822. children[i].computeAbsoluteTransforms();
  79823. }
  79824. };
  79825. /**
  79826. * Get the world direction from an axis that is in the local space of the bone
  79827. * @param localAxis The local direction that is used to compute the world direction
  79828. * @param mesh The mesh that this bone is attached to
  79829. * @returns The world direction
  79830. */
  79831. Bone.prototype.getDirection = function (localAxis, mesh) {
  79832. if (mesh === void 0) { mesh = null; }
  79833. var result = BABYLON.Vector3.Zero();
  79834. this.getDirectionToRef(localAxis, mesh, result);
  79835. return result;
  79836. };
  79837. /**
  79838. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79839. * @param localAxis The local direction that is used to compute the world direction
  79840. * @param mesh The mesh that this bone is attached to
  79841. * @param result The vector3 that the world direction will be copied to
  79842. */
  79843. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79844. if (mesh === void 0) { mesh = null; }
  79845. var wm = null;
  79846. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79847. if (mesh) {
  79848. wm = mesh.getWorldMatrix();
  79849. }
  79850. this._skeleton.computeAbsoluteTransforms();
  79851. var mat = Bone._tmpMats[0];
  79852. mat.copyFrom(this.getAbsoluteTransform());
  79853. if (mesh && wm) {
  79854. mat.multiplyToRef(wm, mat);
  79855. }
  79856. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79857. result.normalize();
  79858. };
  79859. /**
  79860. * Get the euler rotation of the bone in local or world space
  79861. * @param space The space that the rotation should be in
  79862. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79863. * @returns The euler rotation
  79864. */
  79865. Bone.prototype.getRotation = function (space, mesh) {
  79866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79867. if (mesh === void 0) { mesh = null; }
  79868. var result = BABYLON.Vector3.Zero();
  79869. this.getRotationToRef(space, mesh, result);
  79870. return result;
  79871. };
  79872. /**
  79873. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79874. * @param space The space that the rotation should be in
  79875. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79876. * @param result The vector3 that the rotation should be copied to
  79877. */
  79878. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79880. if (mesh === void 0) { mesh = null; }
  79881. var quat = Bone._tmpQuat;
  79882. this.getRotationQuaternionToRef(space, mesh, quat);
  79883. quat.toEulerAnglesToRef(result);
  79884. };
  79885. /**
  79886. * Get the quaternion rotation of the bone in either local or world space
  79887. * @param space The space that the rotation should be in
  79888. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79889. * @returns The quaternion rotation
  79890. */
  79891. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79893. if (mesh === void 0) { mesh = null; }
  79894. var result = BABYLON.Quaternion.Identity();
  79895. this.getRotationQuaternionToRef(space, mesh, result);
  79896. return result;
  79897. };
  79898. /**
  79899. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79900. * @param space The space that the rotation should be in
  79901. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79902. * @param result The quaternion that the rotation should be copied to
  79903. */
  79904. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79906. if (mesh === void 0) { mesh = null; }
  79907. if (space == BABYLON.Space.LOCAL) {
  79908. this._decompose();
  79909. result.copyFrom(this._localRotation);
  79910. }
  79911. else {
  79912. var mat = Bone._tmpMats[0];
  79913. var amat = this.getAbsoluteTransform();
  79914. if (mesh) {
  79915. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79916. }
  79917. else {
  79918. mat.copyFrom(amat);
  79919. }
  79920. mat.m[0] *= this._scalingDeterminant;
  79921. mat.m[1] *= this._scalingDeterminant;
  79922. mat.m[2] *= this._scalingDeterminant;
  79923. mat.decompose(undefined, result, undefined);
  79924. }
  79925. };
  79926. /**
  79927. * Get the rotation matrix of the bone in local or world space
  79928. * @param space The space that the rotation should be in
  79929. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79930. * @returns The rotation matrix
  79931. */
  79932. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79934. var result = BABYLON.Matrix.Identity();
  79935. this.getRotationMatrixToRef(space, mesh, result);
  79936. return result;
  79937. };
  79938. /**
  79939. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79940. * @param space The space that the rotation should be in
  79941. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79942. * @param result The quaternion that the rotation should be copied to
  79943. */
  79944. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79946. if (space == BABYLON.Space.LOCAL) {
  79947. this.getLocalMatrix().getRotationMatrixToRef(result);
  79948. }
  79949. else {
  79950. var mat = Bone._tmpMats[0];
  79951. var amat = this.getAbsoluteTransform();
  79952. if (mesh) {
  79953. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79954. }
  79955. else {
  79956. mat.copyFrom(amat);
  79957. }
  79958. mat.m[0] *= this._scalingDeterminant;
  79959. mat.m[1] *= this._scalingDeterminant;
  79960. mat.m[2] *= this._scalingDeterminant;
  79961. mat.getRotationMatrixToRef(result);
  79962. }
  79963. };
  79964. /**
  79965. * Get the world position of a point that is in the local space of the bone
  79966. * @param position The local position
  79967. * @param mesh The mesh that this bone is attached to
  79968. * @returns The world position
  79969. */
  79970. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79971. if (mesh === void 0) { mesh = null; }
  79972. var result = BABYLON.Vector3.Zero();
  79973. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79974. return result;
  79975. };
  79976. /**
  79977. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79978. * @param position The local position
  79979. * @param mesh The mesh that this bone is attached to
  79980. * @param result The vector3 that the world position should be copied to
  79981. */
  79982. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79983. if (mesh === void 0) { mesh = null; }
  79984. var wm = null;
  79985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79986. if (mesh) {
  79987. wm = mesh.getWorldMatrix();
  79988. }
  79989. this._skeleton.computeAbsoluteTransforms();
  79990. var tmat = Bone._tmpMats[0];
  79991. if (mesh && wm) {
  79992. tmat.copyFrom(this.getAbsoluteTransform());
  79993. tmat.multiplyToRef(wm, tmat);
  79994. }
  79995. else {
  79996. tmat = this.getAbsoluteTransform();
  79997. }
  79998. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79999. };
  80000. /**
  80001. * Get the local position of a point that is in world space
  80002. * @param position The world position
  80003. * @param mesh The mesh that this bone is attached to
  80004. * @returns The local position
  80005. */
  80006. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80007. if (mesh === void 0) { mesh = null; }
  80008. var result = BABYLON.Vector3.Zero();
  80009. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80010. return result;
  80011. };
  80012. /**
  80013. * Get the local position of a point that is in world space and copy it to the result param
  80014. * @param position The world position
  80015. * @param mesh The mesh that this bone is attached to
  80016. * @param result The vector3 that the local position should be copied to
  80017. */
  80018. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80019. if (mesh === void 0) { mesh = null; }
  80020. var wm = null;
  80021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80022. if (mesh) {
  80023. wm = mesh.getWorldMatrix();
  80024. }
  80025. this._skeleton.computeAbsoluteTransforms();
  80026. var tmat = Bone._tmpMats[0];
  80027. tmat.copyFrom(this.getAbsoluteTransform());
  80028. if (mesh && wm) {
  80029. tmat.multiplyToRef(wm, tmat);
  80030. }
  80031. tmat.invert();
  80032. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80033. };
  80034. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80035. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80036. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80037. return Bone;
  80038. }(BABYLON.Node));
  80039. BABYLON.Bone = Bone;
  80040. })(BABYLON || (BABYLON = {}));
  80041. //# sourceMappingURL=babylon.bone.js.map
  80042. var BABYLON;
  80043. (function (BABYLON) {
  80044. /**
  80045. * Class used to apply inverse kinematics to bones
  80046. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80047. */
  80048. var BoneIKController = /** @class */ (function () {
  80049. /**
  80050. * Creates a new BoneIKController
  80051. * @param mesh defines the mesh to control
  80052. * @param bone defines the bone to control
  80053. * @param options defines options to set up the controller
  80054. */
  80055. function BoneIKController(mesh, bone, options) {
  80056. /**
  80057. * Gets or sets the target position
  80058. */
  80059. this.targetPosition = BABYLON.Vector3.Zero();
  80060. /**
  80061. * Gets or sets the pole target position
  80062. */
  80063. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80064. /**
  80065. * Gets or sets the pole target local offset
  80066. */
  80067. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80068. /**
  80069. * Gets or sets the pole angle
  80070. */
  80071. this.poleAngle = 0;
  80072. /**
  80073. * 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)
  80074. */
  80075. this.slerpAmount = 1;
  80076. this._bone1Quat = BABYLON.Quaternion.Identity();
  80077. this._bone1Mat = BABYLON.Matrix.Identity();
  80078. this._bone2Ang = Math.PI;
  80079. this._maxAngle = Math.PI;
  80080. this._rightHandedSystem = false;
  80081. this._bendAxis = BABYLON.Vector3.Right();
  80082. this._slerping = false;
  80083. this._adjustRoll = 0;
  80084. this._bone2 = bone;
  80085. this._bone1 = bone.getParent();
  80086. if (!this._bone1) {
  80087. return;
  80088. }
  80089. this.mesh = mesh;
  80090. var bonePos = bone.getPosition();
  80091. if (bone.getAbsoluteTransform().determinant() > 0) {
  80092. this._rightHandedSystem = true;
  80093. this._bendAxis.x = 0;
  80094. this._bendAxis.y = 0;
  80095. this._bendAxis.z = -1;
  80096. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80097. this._adjustRoll = Math.PI * .5;
  80098. this._bendAxis.z = 1;
  80099. }
  80100. }
  80101. if (this._bone1.length) {
  80102. var boneScale1 = this._bone1.getScale();
  80103. var boneScale2 = this._bone2.getScale();
  80104. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80105. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80106. }
  80107. else if (this._bone1.children[0]) {
  80108. mesh.computeWorldMatrix(true);
  80109. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80110. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80111. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80112. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80113. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80114. }
  80115. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80116. this.maxAngle = Math.PI;
  80117. if (options) {
  80118. if (options.targetMesh) {
  80119. this.targetMesh = options.targetMesh;
  80120. this.targetMesh.computeWorldMatrix(true);
  80121. }
  80122. if (options.poleTargetMesh) {
  80123. this.poleTargetMesh = options.poleTargetMesh;
  80124. this.poleTargetMesh.computeWorldMatrix(true);
  80125. }
  80126. else if (options.poleTargetBone) {
  80127. this.poleTargetBone = options.poleTargetBone;
  80128. }
  80129. else if (this._bone1.getParent()) {
  80130. this.poleTargetBone = this._bone1.getParent();
  80131. }
  80132. if (options.poleTargetLocalOffset) {
  80133. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80134. }
  80135. if (options.poleAngle) {
  80136. this.poleAngle = options.poleAngle;
  80137. }
  80138. if (options.bendAxis) {
  80139. this._bendAxis.copyFrom(options.bendAxis);
  80140. }
  80141. if (options.maxAngle) {
  80142. this.maxAngle = options.maxAngle;
  80143. }
  80144. if (options.slerpAmount) {
  80145. this.slerpAmount = options.slerpAmount;
  80146. }
  80147. }
  80148. }
  80149. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80150. /**
  80151. * Gets or sets maximum allowed angle
  80152. */
  80153. get: function () {
  80154. return this._maxAngle;
  80155. },
  80156. set: function (value) {
  80157. this._setMaxAngle(value);
  80158. },
  80159. enumerable: true,
  80160. configurable: true
  80161. });
  80162. BoneIKController.prototype._setMaxAngle = function (ang) {
  80163. if (ang < 0) {
  80164. ang = 0;
  80165. }
  80166. if (ang > Math.PI || ang == undefined) {
  80167. ang = Math.PI;
  80168. }
  80169. this._maxAngle = ang;
  80170. var a = this._bone1Length;
  80171. var b = this._bone2Length;
  80172. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80173. };
  80174. /**
  80175. * Force the controller to update the bones
  80176. */
  80177. BoneIKController.prototype.update = function () {
  80178. var bone1 = this._bone1;
  80179. if (!bone1) {
  80180. return;
  80181. }
  80182. var target = this.targetPosition;
  80183. var poleTarget = this.poleTargetPosition;
  80184. var mat1 = BoneIKController._tmpMats[0];
  80185. var mat2 = BoneIKController._tmpMats[1];
  80186. if (this.targetMesh) {
  80187. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80188. }
  80189. if (this.poleTargetBone) {
  80190. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80191. }
  80192. else if (this.poleTargetMesh) {
  80193. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80194. }
  80195. var bonePos = BoneIKController._tmpVecs[0];
  80196. var zaxis = BoneIKController._tmpVecs[1];
  80197. var xaxis = BoneIKController._tmpVecs[2];
  80198. var yaxis = BoneIKController._tmpVecs[3];
  80199. var upAxis = BoneIKController._tmpVecs[4];
  80200. var _tmpQuat = BoneIKController._tmpQuat;
  80201. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80202. poleTarget.subtractToRef(bonePos, upAxis);
  80203. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80204. upAxis.y = 1;
  80205. }
  80206. else {
  80207. upAxis.normalize();
  80208. }
  80209. target.subtractToRef(bonePos, yaxis);
  80210. yaxis.normalize();
  80211. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80212. zaxis.normalize();
  80213. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80214. xaxis.normalize();
  80215. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80216. var a = this._bone1Length;
  80217. var b = this._bone2Length;
  80218. var c = BABYLON.Vector3.Distance(bonePos, target);
  80219. if (this._maxReach > 0) {
  80220. c = Math.min(this._maxReach, c);
  80221. }
  80222. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80223. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80224. if (acosa > 1) {
  80225. acosa = 1;
  80226. }
  80227. if (acosb > 1) {
  80228. acosb = 1;
  80229. }
  80230. if (acosa < -1) {
  80231. acosa = -1;
  80232. }
  80233. if (acosb < -1) {
  80234. acosb = -1;
  80235. }
  80236. var angA = Math.acos(acosa);
  80237. var angB = Math.acos(acosb);
  80238. var angC = -angA - angB;
  80239. if (this._rightHandedSystem) {
  80240. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80241. mat2.multiplyToRef(mat1, mat1);
  80242. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80243. mat2.multiplyToRef(mat1, mat1);
  80244. }
  80245. else {
  80246. var _tmpVec = BoneIKController._tmpVecs[5];
  80247. _tmpVec.copyFrom(this._bendAxis);
  80248. _tmpVec.x *= -1;
  80249. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80250. mat2.multiplyToRef(mat1, mat1);
  80251. }
  80252. if (this.poleAngle) {
  80253. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80254. mat1.multiplyToRef(mat2, mat1);
  80255. }
  80256. if (this._bone1) {
  80257. if (this.slerpAmount < 1) {
  80258. if (!this._slerping) {
  80259. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80260. }
  80261. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80262. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80263. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80264. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80265. this._slerping = true;
  80266. }
  80267. else {
  80268. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80269. this._bone1Mat.copyFrom(mat1);
  80270. this._slerping = false;
  80271. }
  80272. }
  80273. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80274. this._bone2Ang = angC;
  80275. };
  80276. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80277. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80278. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80279. return BoneIKController;
  80280. }());
  80281. BABYLON.BoneIKController = BoneIKController;
  80282. })(BABYLON || (BABYLON = {}));
  80283. //# sourceMappingURL=babylon.boneIKController.js.map
  80284. var BABYLON;
  80285. (function (BABYLON) {
  80286. /**
  80287. * Class used to make a bone look toward a point in space
  80288. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80289. */
  80290. var BoneLookController = /** @class */ (function () {
  80291. /**
  80292. * Create a BoneLookController
  80293. * @param mesh the mesh that the bone belongs to
  80294. * @param bone the bone that will be looking to the target
  80295. * @param target the target Vector3 to look at
  80296. * @param settings optional settings:
  80297. * * maxYaw: the maximum angle the bone will yaw to
  80298. * * minYaw: the minimum angle the bone will yaw to
  80299. * * maxPitch: the maximum angle the bone will pitch to
  80300. * * minPitch: the minimum angle the bone will yaw to
  80301. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80302. * * upAxis: the up axis of the coordinate system
  80303. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80304. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80305. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80306. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80307. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80308. * * adjustRoll: used to make an adjustment to the roll of the bone
  80309. **/
  80310. function BoneLookController(mesh, bone, target, options) {
  80311. /**
  80312. * The up axis of the coordinate system that is used when the bone is rotated
  80313. */
  80314. this.upAxis = BABYLON.Vector3.Up();
  80315. /**
  80316. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80317. */
  80318. this.upAxisSpace = BABYLON.Space.LOCAL;
  80319. /**
  80320. * Used to make an adjustment to the yaw of the bone
  80321. */
  80322. this.adjustYaw = 0;
  80323. /**
  80324. * Used to make an adjustment to the pitch of the bone
  80325. */
  80326. this.adjustPitch = 0;
  80327. /**
  80328. * Used to make an adjustment to the roll of the bone
  80329. */
  80330. this.adjustRoll = 0;
  80331. /**
  80332. * 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)
  80333. */
  80334. this.slerpAmount = 1;
  80335. this._boneQuat = BABYLON.Quaternion.Identity();
  80336. this._slerping = false;
  80337. this._firstFrameSkipped = false;
  80338. this._fowardAxis = BABYLON.Vector3.Forward();
  80339. this.mesh = mesh;
  80340. this.bone = bone;
  80341. this.target = target;
  80342. if (options) {
  80343. if (options.adjustYaw) {
  80344. this.adjustYaw = options.adjustYaw;
  80345. }
  80346. if (options.adjustPitch) {
  80347. this.adjustPitch = options.adjustPitch;
  80348. }
  80349. if (options.adjustRoll) {
  80350. this.adjustRoll = options.adjustRoll;
  80351. }
  80352. if (options.maxYaw != null) {
  80353. this.maxYaw = options.maxYaw;
  80354. }
  80355. else {
  80356. this.maxYaw = Math.PI;
  80357. }
  80358. if (options.minYaw != null) {
  80359. this.minYaw = options.minYaw;
  80360. }
  80361. else {
  80362. this.minYaw = -Math.PI;
  80363. }
  80364. if (options.maxPitch != null) {
  80365. this.maxPitch = options.maxPitch;
  80366. }
  80367. else {
  80368. this.maxPitch = Math.PI;
  80369. }
  80370. if (options.minPitch != null) {
  80371. this.minPitch = options.minPitch;
  80372. }
  80373. else {
  80374. this.minPitch = -Math.PI;
  80375. }
  80376. if (options.slerpAmount != null) {
  80377. this.slerpAmount = options.slerpAmount;
  80378. }
  80379. if (options.upAxis != null) {
  80380. this.upAxis = options.upAxis;
  80381. }
  80382. if (options.upAxisSpace != null) {
  80383. this.upAxisSpace = options.upAxisSpace;
  80384. }
  80385. if (options.yawAxis != null || options.pitchAxis != null) {
  80386. var newYawAxis = BABYLON.Axis.Y;
  80387. var newPitchAxis = BABYLON.Axis.X;
  80388. if (options.yawAxis != null) {
  80389. newYawAxis = options.yawAxis.clone();
  80390. newYawAxis.normalize();
  80391. }
  80392. if (options.pitchAxis != null) {
  80393. newPitchAxis = options.pitchAxis.clone();
  80394. newPitchAxis.normalize();
  80395. }
  80396. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80397. this._transformYawPitch = BABYLON.Matrix.Identity();
  80398. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80399. this._transformYawPitchInv = this._transformYawPitch.clone();
  80400. this._transformYawPitch.invert();
  80401. }
  80402. }
  80403. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80404. this.upAxisSpace = BABYLON.Space.LOCAL;
  80405. }
  80406. }
  80407. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80408. /**
  80409. * Gets or sets the minimum yaw angle that the bone can look to
  80410. */
  80411. get: function () {
  80412. return this._minYaw;
  80413. },
  80414. set: function (value) {
  80415. this._minYaw = value;
  80416. this._minYawSin = Math.sin(value);
  80417. this._minYawCos = Math.cos(value);
  80418. if (this._maxYaw != null) {
  80419. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80420. this._yawRange = this._maxYaw - this._minYaw;
  80421. }
  80422. },
  80423. enumerable: true,
  80424. configurable: true
  80425. });
  80426. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80427. /**
  80428. * Gets or sets the maximum yaw angle that the bone can look to
  80429. */
  80430. get: function () {
  80431. return this._maxYaw;
  80432. },
  80433. set: function (value) {
  80434. this._maxYaw = value;
  80435. this._maxYawSin = Math.sin(value);
  80436. this._maxYawCos = Math.cos(value);
  80437. if (this._minYaw != null) {
  80438. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80439. this._yawRange = this._maxYaw - this._minYaw;
  80440. }
  80441. },
  80442. enumerable: true,
  80443. configurable: true
  80444. });
  80445. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80446. /**
  80447. * Gets or sets the minimum pitch angle that the bone can look to
  80448. */
  80449. get: function () {
  80450. return this._minPitch;
  80451. },
  80452. set: function (value) {
  80453. this._minPitch = value;
  80454. this._minPitchTan = Math.tan(value);
  80455. },
  80456. enumerable: true,
  80457. configurable: true
  80458. });
  80459. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80460. /**
  80461. * Gets or sets the maximum pitch angle that the bone can look to
  80462. */
  80463. get: function () {
  80464. return this._maxPitch;
  80465. },
  80466. set: function (value) {
  80467. this._maxPitch = value;
  80468. this._maxPitchTan = Math.tan(value);
  80469. },
  80470. enumerable: true,
  80471. configurable: true
  80472. });
  80473. /**
  80474. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80475. */
  80476. BoneLookController.prototype.update = function () {
  80477. //skip the first frame when slerping so that the mesh rotation is correct
  80478. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80479. this._firstFrameSkipped = true;
  80480. return;
  80481. }
  80482. var bone = this.bone;
  80483. var bonePos = BoneLookController._tmpVecs[0];
  80484. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80485. var target = this.target;
  80486. var _tmpMat1 = BoneLookController._tmpMats[0];
  80487. var _tmpMat2 = BoneLookController._tmpMats[1];
  80488. var mesh = this.mesh;
  80489. var parentBone = bone.getParent();
  80490. var upAxis = BoneLookController._tmpVecs[1];
  80491. upAxis.copyFrom(this.upAxis);
  80492. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80493. if (this._transformYawPitch) {
  80494. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80495. }
  80496. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80497. }
  80498. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80499. mesh.getDirectionToRef(upAxis, upAxis);
  80500. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80501. upAxis.normalize();
  80502. }
  80503. }
  80504. var checkYaw = false;
  80505. var checkPitch = false;
  80506. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80507. checkYaw = true;
  80508. }
  80509. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80510. checkPitch = true;
  80511. }
  80512. if (checkYaw || checkPitch) {
  80513. var spaceMat = BoneLookController._tmpMats[2];
  80514. var spaceMatInv = BoneLookController._tmpMats[3];
  80515. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80516. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80517. }
  80518. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80519. spaceMat.copyFrom(mesh.getWorldMatrix());
  80520. }
  80521. else {
  80522. var forwardAxis = BoneLookController._tmpVecs[2];
  80523. forwardAxis.copyFrom(this._fowardAxis);
  80524. if (this._transformYawPitch) {
  80525. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80526. }
  80527. if (parentBone) {
  80528. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80529. }
  80530. else {
  80531. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80532. }
  80533. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80534. rightAxis.normalize();
  80535. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80536. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80537. }
  80538. spaceMat.invertToRef(spaceMatInv);
  80539. var xzlen = null;
  80540. if (checkPitch) {
  80541. var localTarget = BoneLookController._tmpVecs[3];
  80542. target.subtractToRef(bonePos, localTarget);
  80543. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80544. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80545. var pitch = Math.atan2(localTarget.y, xzlen);
  80546. var newPitch = pitch;
  80547. if (pitch > this._maxPitch) {
  80548. localTarget.y = this._maxPitchTan * xzlen;
  80549. newPitch = this._maxPitch;
  80550. }
  80551. else if (pitch < this._minPitch) {
  80552. localTarget.y = this._minPitchTan * xzlen;
  80553. newPitch = this._minPitch;
  80554. }
  80555. if (pitch != newPitch) {
  80556. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80557. localTarget.addInPlace(bonePos);
  80558. target = localTarget;
  80559. }
  80560. }
  80561. if (checkYaw) {
  80562. var localTarget = BoneLookController._tmpVecs[4];
  80563. target.subtractToRef(bonePos, localTarget);
  80564. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80565. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80566. var newYaw = yaw;
  80567. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80568. if (xzlen == null) {
  80569. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80570. }
  80571. if (this._yawRange > Math.PI) {
  80572. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80573. localTarget.z = this._maxYawCos * xzlen;
  80574. localTarget.x = this._maxYawSin * xzlen;
  80575. newYaw = this._maxYaw;
  80576. }
  80577. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80578. localTarget.z = this._minYawCos * xzlen;
  80579. localTarget.x = this._minYawSin * xzlen;
  80580. newYaw = this._minYaw;
  80581. }
  80582. }
  80583. else {
  80584. if (yaw > this._maxYaw) {
  80585. localTarget.z = this._maxYawCos * xzlen;
  80586. localTarget.x = this._maxYawSin * xzlen;
  80587. newYaw = this._maxYaw;
  80588. }
  80589. else if (yaw < this._minYaw) {
  80590. localTarget.z = this._minYawCos * xzlen;
  80591. localTarget.x = this._minYawSin * xzlen;
  80592. newYaw = this._minYaw;
  80593. }
  80594. }
  80595. }
  80596. if (this._slerping && this._yawRange > Math.PI) {
  80597. //are we going to be crossing into the min/max region?
  80598. var boneFwd = BoneLookController._tmpVecs[8];
  80599. boneFwd.copyFrom(BABYLON.Axis.Z);
  80600. if (this._transformYawPitch) {
  80601. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80602. }
  80603. var boneRotMat = BoneLookController._tmpMats[4];
  80604. this._boneQuat.toRotationMatrix(boneRotMat);
  80605. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80606. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80607. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80608. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80609. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80610. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80611. if (angBtwTar > angBtwMidYaw) {
  80612. if (xzlen == null) {
  80613. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80614. }
  80615. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80616. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80617. if (angBtwMin < angBtwMax) {
  80618. newYaw = boneYaw + Math.PI * .75;
  80619. localTarget.z = Math.cos(newYaw) * xzlen;
  80620. localTarget.x = Math.sin(newYaw) * xzlen;
  80621. }
  80622. else {
  80623. newYaw = boneYaw - Math.PI * .75;
  80624. localTarget.z = Math.cos(newYaw) * xzlen;
  80625. localTarget.x = Math.sin(newYaw) * xzlen;
  80626. }
  80627. }
  80628. }
  80629. if (yaw != newYaw) {
  80630. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80631. localTarget.addInPlace(bonePos);
  80632. target = localTarget;
  80633. }
  80634. }
  80635. }
  80636. var zaxis = BoneLookController._tmpVecs[5];
  80637. var xaxis = BoneLookController._tmpVecs[6];
  80638. var yaxis = BoneLookController._tmpVecs[7];
  80639. var _tmpQuat = BoneLookController._tmpQuat;
  80640. target.subtractToRef(bonePos, zaxis);
  80641. zaxis.normalize();
  80642. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80643. xaxis.normalize();
  80644. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80645. yaxis.normalize();
  80646. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80647. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80648. return;
  80649. }
  80650. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80651. return;
  80652. }
  80653. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80654. return;
  80655. }
  80656. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80657. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80658. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80659. }
  80660. if (this.slerpAmount < 1) {
  80661. if (!this._slerping) {
  80662. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80663. }
  80664. if (this._transformYawPitch) {
  80665. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80666. }
  80667. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80668. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80669. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80670. this._slerping = true;
  80671. }
  80672. else {
  80673. if (this._transformYawPitch) {
  80674. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80675. }
  80676. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80677. this._slerping = false;
  80678. }
  80679. };
  80680. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80681. var angDiff = ang2 - ang1;
  80682. angDiff %= Math.PI * 2;
  80683. if (angDiff > Math.PI) {
  80684. angDiff -= Math.PI * 2;
  80685. }
  80686. else if (angDiff < -Math.PI) {
  80687. angDiff += Math.PI * 2;
  80688. }
  80689. return angDiff;
  80690. };
  80691. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80692. ang1 %= (2 * Math.PI);
  80693. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80694. ang2 %= (2 * Math.PI);
  80695. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80696. var ab = 0;
  80697. if (ang1 < ang2) {
  80698. ab = ang2 - ang1;
  80699. }
  80700. else {
  80701. ab = ang1 - ang2;
  80702. }
  80703. if (ab > Math.PI) {
  80704. ab = Math.PI * 2 - ab;
  80705. }
  80706. return ab;
  80707. };
  80708. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80709. ang %= (2 * Math.PI);
  80710. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80711. ang1 %= (2 * Math.PI);
  80712. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80713. ang2 %= (2 * Math.PI);
  80714. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80715. if (ang1 < ang2) {
  80716. if (ang > ang1 && ang < ang2) {
  80717. return true;
  80718. }
  80719. }
  80720. else {
  80721. if (ang > ang2 && ang < ang1) {
  80722. return true;
  80723. }
  80724. }
  80725. return false;
  80726. };
  80727. 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()];
  80728. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80729. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80730. return BoneLookController;
  80731. }());
  80732. BABYLON.BoneLookController = BoneLookController;
  80733. })(BABYLON || (BABYLON = {}));
  80734. //# sourceMappingURL=babylon.boneLookController.js.map
  80735. var BABYLON;
  80736. (function (BABYLON) {
  80737. /**
  80738. * Class used to handle skinning animations
  80739. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80740. */
  80741. var Skeleton = /** @class */ (function () {
  80742. /**
  80743. * Creates a new skeleton
  80744. * @param name defines the skeleton name
  80745. * @param id defines the skeleton Id
  80746. * @param scene defines the hosting scene
  80747. */
  80748. function Skeleton(
  80749. /** defines the skeleton name */
  80750. name,
  80751. /** defines the skeleton Id */
  80752. id, scene) {
  80753. this.name = name;
  80754. this.id = id;
  80755. /**
  80756. * Gets the list of child bones
  80757. */
  80758. this.bones = new Array();
  80759. /**
  80760. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80761. */
  80762. this.needInitialSkinMatrix = false;
  80763. this._isDirty = true;
  80764. this._meshesWithPoseMatrix = new Array();
  80765. this._identity = BABYLON.Matrix.Identity();
  80766. this._ranges = {};
  80767. this._lastAbsoluteTransformsUpdateId = -1;
  80768. /**
  80769. * Specifies if the skeleton should be serialized
  80770. */
  80771. this.doNotSerialize = false;
  80772. this._animationPropertiesOverride = null;
  80773. // Events
  80774. /**
  80775. * An observable triggered before computing the skeleton's matrices
  80776. */
  80777. this.onBeforeComputeObservable = new BABYLON.Observable();
  80778. this.bones = [];
  80779. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80780. scene.skeletons.push(this);
  80781. //make sure it will recalculate the matrix next time prepare is called.
  80782. this._isDirty = true;
  80783. }
  80784. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80785. /**
  80786. * Gets or sets the animation properties override
  80787. */
  80788. get: function () {
  80789. if (!this._animationPropertiesOverride) {
  80790. return this._scene.animationPropertiesOverride;
  80791. }
  80792. return this._animationPropertiesOverride;
  80793. },
  80794. set: function (value) {
  80795. this._animationPropertiesOverride = value;
  80796. },
  80797. enumerable: true,
  80798. configurable: true
  80799. });
  80800. // Members
  80801. /**
  80802. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80803. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80804. * @returns a Float32Array containing matrices data
  80805. */
  80806. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80807. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80808. return mesh._bonesTransformMatrices;
  80809. }
  80810. if (!this._transformMatrices) {
  80811. this.prepare();
  80812. }
  80813. return this._transformMatrices;
  80814. };
  80815. /**
  80816. * Gets the current hosting scene
  80817. * @returns a scene object
  80818. */
  80819. Skeleton.prototype.getScene = function () {
  80820. return this._scene;
  80821. };
  80822. // Methods
  80823. /**
  80824. * Gets a string representing the current skeleton data
  80825. * @param fullDetails defines a boolean indicating if we want a verbose version
  80826. * @returns a string representing the current skeleton data
  80827. */
  80828. Skeleton.prototype.toString = function (fullDetails) {
  80829. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80830. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80831. if (fullDetails) {
  80832. ret += ", Ranges: {";
  80833. var first = true;
  80834. for (var name_1 in this._ranges) {
  80835. if (first) {
  80836. ret += ", ";
  80837. first = false;
  80838. }
  80839. ret += name_1;
  80840. }
  80841. ret += "}";
  80842. }
  80843. return ret;
  80844. };
  80845. /**
  80846. * Get bone's index searching by name
  80847. * @param name defines bone's name to search for
  80848. * @return the indice of the bone. Returns -1 if not found
  80849. */
  80850. Skeleton.prototype.getBoneIndexByName = function (name) {
  80851. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80852. if (this.bones[boneIndex].name === name) {
  80853. return boneIndex;
  80854. }
  80855. }
  80856. return -1;
  80857. };
  80858. /**
  80859. * Creater a new animation range
  80860. * @param name defines the name of the range
  80861. * @param from defines the start key
  80862. * @param to defines the end key
  80863. */
  80864. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80865. // check name not already in use
  80866. if (!this._ranges[name]) {
  80867. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80868. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80869. if (this.bones[i].animations[0]) {
  80870. this.bones[i].animations[0].createRange(name, from, to);
  80871. }
  80872. }
  80873. }
  80874. };
  80875. /**
  80876. * Delete a specific animation range
  80877. * @param name defines the name of the range
  80878. * @param deleteFrames defines if frames must be removed as well
  80879. */
  80880. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80881. if (deleteFrames === void 0) { deleteFrames = true; }
  80882. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80883. if (this.bones[i].animations[0]) {
  80884. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80885. }
  80886. }
  80887. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80888. };
  80889. /**
  80890. * Gets a specific animation range
  80891. * @param name defines the name of the range to look for
  80892. * @returns the requested animation range or null if not found
  80893. */
  80894. Skeleton.prototype.getAnimationRange = function (name) {
  80895. return this._ranges[name];
  80896. };
  80897. /**
  80898. * Gets the list of all animation ranges defined on this skeleton
  80899. * @returns an array
  80900. */
  80901. Skeleton.prototype.getAnimationRanges = function () {
  80902. var animationRanges = [];
  80903. var name;
  80904. var i = 0;
  80905. for (name in this._ranges) {
  80906. animationRanges[i] = this._ranges[name];
  80907. i++;
  80908. }
  80909. return animationRanges;
  80910. };
  80911. /**
  80912. * Copy animation range from a source skeleton.
  80913. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80914. * @param source defines the source skeleton
  80915. * @param name defines the name of the range to copy
  80916. * @param rescaleAsRequired defines if rescaling must be applied if required
  80917. * @returns true if operation was successful
  80918. */
  80919. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80920. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80921. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80922. return false;
  80923. }
  80924. var ret = true;
  80925. var frameOffset = this._getHighestAnimationFrame() + 1;
  80926. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80927. var boneDict = {};
  80928. var sourceBones = source.bones;
  80929. var nBones;
  80930. var i;
  80931. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80932. boneDict[sourceBones[i].name] = sourceBones[i];
  80933. }
  80934. if (this.bones.length !== sourceBones.length) {
  80935. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80936. ret = false;
  80937. }
  80938. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80939. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80940. var boneName = this.bones[i].name;
  80941. var sourceBone = boneDict[boneName];
  80942. if (sourceBone) {
  80943. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80944. }
  80945. else {
  80946. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80947. ret = false;
  80948. }
  80949. }
  80950. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80951. var range = source.getAnimationRange(name);
  80952. if (range) {
  80953. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80954. }
  80955. return ret;
  80956. };
  80957. /**
  80958. * Forces the skeleton to go to rest pose
  80959. */
  80960. Skeleton.prototype.returnToRest = function () {
  80961. for (var index = 0; index < this.bones.length; index++) {
  80962. this.bones[index].returnToRest();
  80963. }
  80964. };
  80965. Skeleton.prototype._getHighestAnimationFrame = function () {
  80966. var ret = 0;
  80967. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80968. if (this.bones[i].animations[0]) {
  80969. var highest = this.bones[i].animations[0].getHighestFrame();
  80970. if (ret < highest) {
  80971. ret = highest;
  80972. }
  80973. }
  80974. }
  80975. return ret;
  80976. };
  80977. /**
  80978. * Begin a specific animation range
  80979. * @param name defines the name of the range to start
  80980. * @param loop defines if looping must be turned on (false by default)
  80981. * @param speedRatio defines the speed ratio to apply (1 by default)
  80982. * @param onAnimationEnd defines a callback which will be called when animation will end
  80983. * @returns a new animatable
  80984. */
  80985. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80986. var range = this.getAnimationRange(name);
  80987. if (!range) {
  80988. return null;
  80989. }
  80990. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80991. };
  80992. /** @hidden */
  80993. Skeleton.prototype._markAsDirty = function () {
  80994. this._isDirty = true;
  80995. };
  80996. /** @hidden */
  80997. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80998. this._meshesWithPoseMatrix.push(mesh);
  80999. };
  81000. /** @hidden */
  81001. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81002. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81003. if (index > -1) {
  81004. this._meshesWithPoseMatrix.splice(index, 1);
  81005. }
  81006. };
  81007. /** @hidden */
  81008. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81009. this.onBeforeComputeObservable.notifyObservers(this);
  81010. for (var index = 0; index < this.bones.length; index++) {
  81011. var bone = this.bones[index];
  81012. var parentBone = bone.getParent();
  81013. if (parentBone) {
  81014. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81015. }
  81016. else {
  81017. if (initialSkinMatrix) {
  81018. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81019. }
  81020. else {
  81021. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81022. }
  81023. }
  81024. if (bone._index !== -1) {
  81025. var mappedIndex = bone._index === null ? index : bone._index;
  81026. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81027. }
  81028. }
  81029. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81030. };
  81031. /**
  81032. * Build all resources required to render a skeleton
  81033. */
  81034. Skeleton.prototype.prepare = function () {
  81035. if (!this._isDirty) {
  81036. return;
  81037. }
  81038. if (this.needInitialSkinMatrix) {
  81039. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81040. var mesh = this._meshesWithPoseMatrix[index];
  81041. var poseMatrix = mesh.getPoseMatrix();
  81042. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81043. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81044. }
  81045. if (this._synchronizedWithMesh !== mesh) {
  81046. this._synchronizedWithMesh = mesh;
  81047. // Prepare bones
  81048. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81049. var bone = this.bones[boneIndex];
  81050. if (!bone.getParent()) {
  81051. var matrix = bone.getBaseMatrix();
  81052. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81053. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81054. }
  81055. }
  81056. }
  81057. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81058. }
  81059. }
  81060. else {
  81061. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81062. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81063. }
  81064. this._computeTransformMatrices(this._transformMatrices, null);
  81065. }
  81066. this._isDirty = false;
  81067. this._scene._activeBones.addCount(this.bones.length, false);
  81068. };
  81069. /**
  81070. * Gets the list of animatables currently running for this skeleton
  81071. * @returns an array of animatables
  81072. */
  81073. Skeleton.prototype.getAnimatables = function () {
  81074. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81075. this._animatables = [];
  81076. for (var index = 0; index < this.bones.length; index++) {
  81077. this._animatables.push(this.bones[index]);
  81078. }
  81079. }
  81080. return this._animatables;
  81081. };
  81082. /**
  81083. * Clone the current skeleton
  81084. * @param name defines the name of the new skeleton
  81085. * @param id defines the id of the enw skeleton
  81086. * @returns the new skeleton
  81087. */
  81088. Skeleton.prototype.clone = function (name, id) {
  81089. var result = new Skeleton(name, id || name, this._scene);
  81090. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81091. for (var index = 0; index < this.bones.length; index++) {
  81092. var source = this.bones[index];
  81093. var parentBone = null;
  81094. var parent_1 = source.getParent();
  81095. if (parent_1) {
  81096. var parentIndex = this.bones.indexOf(parent_1);
  81097. parentBone = result.bones[parentIndex];
  81098. }
  81099. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81100. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81101. }
  81102. if (this._ranges) {
  81103. result._ranges = {};
  81104. for (var rangeName in this._ranges) {
  81105. var range = this._ranges[rangeName];
  81106. if (range) {
  81107. result._ranges[rangeName] = range.clone();
  81108. }
  81109. }
  81110. }
  81111. this._isDirty = true;
  81112. return result;
  81113. };
  81114. /**
  81115. * Enable animation blending for this skeleton
  81116. * @param blendingSpeed defines the blending speed to apply
  81117. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81118. */
  81119. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81120. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81121. this.bones.forEach(function (bone) {
  81122. bone.animations.forEach(function (animation) {
  81123. animation.enableBlending = true;
  81124. animation.blendingSpeed = blendingSpeed;
  81125. });
  81126. });
  81127. };
  81128. /**
  81129. * Releases all resources associated with the current skeleton
  81130. */
  81131. Skeleton.prototype.dispose = function () {
  81132. this._meshesWithPoseMatrix = [];
  81133. // Animations
  81134. this.getScene().stopAnimation(this);
  81135. // Remove from scene
  81136. this.getScene().removeSkeleton(this);
  81137. };
  81138. /**
  81139. * Serialize the skeleton in a JSON object
  81140. * @returns a JSON object
  81141. */
  81142. Skeleton.prototype.serialize = function () {
  81143. var serializationObject = {};
  81144. serializationObject.name = this.name;
  81145. serializationObject.id = this.id;
  81146. if (this.dimensionsAtRest) {
  81147. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81148. }
  81149. serializationObject.bones = [];
  81150. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81151. for (var index = 0; index < this.bones.length; index++) {
  81152. var bone = this.bones[index];
  81153. var parent_2 = bone.getParent();
  81154. var serializedBone = {
  81155. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81156. name: bone.name,
  81157. matrix: bone.getBaseMatrix().toArray(),
  81158. rest: bone.getRestPose().toArray()
  81159. };
  81160. serializationObject.bones.push(serializedBone);
  81161. if (bone.length) {
  81162. serializedBone.length = bone.length;
  81163. }
  81164. if (bone.metadata) {
  81165. serializedBone.metadata = bone.metadata;
  81166. }
  81167. if (bone.animations && bone.animations.length > 0) {
  81168. serializedBone.animation = bone.animations[0].serialize();
  81169. }
  81170. serializationObject.ranges = [];
  81171. for (var name in this._ranges) {
  81172. var source = this._ranges[name];
  81173. if (!source) {
  81174. continue;
  81175. }
  81176. var range = {};
  81177. range.name = name;
  81178. range.from = source.from;
  81179. range.to = source.to;
  81180. serializationObject.ranges.push(range);
  81181. }
  81182. }
  81183. return serializationObject;
  81184. };
  81185. /**
  81186. * Creates a new skeleton from serialized data
  81187. * @param parsedSkeleton defines the serialized data
  81188. * @param scene defines the hosting scene
  81189. * @returns a new skeleton
  81190. */
  81191. Skeleton.Parse = function (parsedSkeleton, scene) {
  81192. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81193. if (parsedSkeleton.dimensionsAtRest) {
  81194. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81195. }
  81196. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81197. var index;
  81198. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81199. var parsedBone = parsedSkeleton.bones[index];
  81200. var parentBone = null;
  81201. if (parsedBone.parentBoneIndex > -1) {
  81202. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81203. }
  81204. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81205. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81206. if (parsedBone.length) {
  81207. bone.length = parsedBone.length;
  81208. }
  81209. if (parsedBone.metadata) {
  81210. bone.metadata = parsedBone.metadata;
  81211. }
  81212. if (parsedBone.animation) {
  81213. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81214. }
  81215. }
  81216. // placed after bones, so createAnimationRange can cascade down
  81217. if (parsedSkeleton.ranges) {
  81218. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81219. var data = parsedSkeleton.ranges[index];
  81220. skeleton.createAnimationRange(data.name, data.from, data.to);
  81221. }
  81222. }
  81223. return skeleton;
  81224. };
  81225. /**
  81226. * Compute all node absolute transforms
  81227. * @param forceUpdate defines if computation must be done even if cache is up to date
  81228. */
  81229. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81230. if (forceUpdate === void 0) { forceUpdate = false; }
  81231. var renderId = this._scene.getRenderId();
  81232. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81233. this.bones[0].computeAbsoluteTransforms();
  81234. this._lastAbsoluteTransformsUpdateId = renderId;
  81235. }
  81236. };
  81237. /**
  81238. * Gets the root pose matrix
  81239. * @returns a matrix
  81240. */
  81241. Skeleton.prototype.getPoseMatrix = function () {
  81242. var poseMatrix = null;
  81243. if (this._meshesWithPoseMatrix.length > 0) {
  81244. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81245. }
  81246. return poseMatrix;
  81247. };
  81248. /**
  81249. * Sorts bones per internal index
  81250. */
  81251. Skeleton.prototype.sortBones = function () {
  81252. var bones = new Array();
  81253. var visited = new Array(this.bones.length);
  81254. for (var index = 0; index < this.bones.length; index++) {
  81255. this._sortBones(index, bones, visited);
  81256. }
  81257. this.bones = bones;
  81258. };
  81259. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81260. if (visited[index]) {
  81261. return;
  81262. }
  81263. visited[index] = true;
  81264. var bone = this.bones[index];
  81265. if (bone._index === undefined) {
  81266. bone._index = index;
  81267. }
  81268. var parentBone = bone.getParent();
  81269. if (parentBone) {
  81270. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81271. }
  81272. bones.push(bone);
  81273. };
  81274. return Skeleton;
  81275. }());
  81276. BABYLON.Skeleton = Skeleton;
  81277. })(BABYLON || (BABYLON = {}));
  81278. //# sourceMappingURL=babylon.skeleton.js.map
  81279. var BABYLON;
  81280. (function (BABYLON) {
  81281. var SphericalPolynomial = /** @class */ (function () {
  81282. function SphericalPolynomial() {
  81283. this.x = BABYLON.Vector3.Zero();
  81284. this.y = BABYLON.Vector3.Zero();
  81285. this.z = BABYLON.Vector3.Zero();
  81286. this.xx = BABYLON.Vector3.Zero();
  81287. this.yy = BABYLON.Vector3.Zero();
  81288. this.zz = BABYLON.Vector3.Zero();
  81289. this.xy = BABYLON.Vector3.Zero();
  81290. this.yz = BABYLON.Vector3.Zero();
  81291. this.zx = BABYLON.Vector3.Zero();
  81292. }
  81293. SphericalPolynomial.prototype.addAmbient = function (color) {
  81294. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81295. this.xx = this.xx.add(colorVector);
  81296. this.yy = this.yy.add(colorVector);
  81297. this.zz = this.zz.add(colorVector);
  81298. };
  81299. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81300. var result = new SphericalPolynomial();
  81301. result.x = harmonics.L11.scale(1.02333);
  81302. result.y = harmonics.L1_1.scale(1.02333);
  81303. result.z = harmonics.L10.scale(1.02333);
  81304. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81305. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81306. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81307. result.yz = harmonics.L2_1.scale(0.858086);
  81308. result.zx = harmonics.L21.scale(0.858086);
  81309. result.xy = harmonics.L2_2.scale(0.858086);
  81310. result.scale(1.0 / Math.PI);
  81311. return result;
  81312. };
  81313. SphericalPolynomial.prototype.scale = function (scale) {
  81314. this.x = this.x.scale(scale);
  81315. this.y = this.y.scale(scale);
  81316. this.z = this.z.scale(scale);
  81317. this.xx = this.xx.scale(scale);
  81318. this.yy = this.yy.scale(scale);
  81319. this.zz = this.zz.scale(scale);
  81320. this.yz = this.yz.scale(scale);
  81321. this.zx = this.zx.scale(scale);
  81322. this.xy = this.xy.scale(scale);
  81323. };
  81324. return SphericalPolynomial;
  81325. }());
  81326. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81327. var SphericalHarmonics = /** @class */ (function () {
  81328. function SphericalHarmonics() {
  81329. this.L00 = BABYLON.Vector3.Zero();
  81330. this.L1_1 = BABYLON.Vector3.Zero();
  81331. this.L10 = BABYLON.Vector3.Zero();
  81332. this.L11 = BABYLON.Vector3.Zero();
  81333. this.L2_2 = BABYLON.Vector3.Zero();
  81334. this.L2_1 = BABYLON.Vector3.Zero();
  81335. this.L20 = BABYLON.Vector3.Zero();
  81336. this.L21 = BABYLON.Vector3.Zero();
  81337. this.L22 = BABYLON.Vector3.Zero();
  81338. }
  81339. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81340. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81341. var c = colorVector.scale(deltaSolidAngle);
  81342. this.L00 = this.L00.add(c.scale(0.282095));
  81343. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81344. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81345. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81346. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81347. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81348. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81349. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81350. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81351. };
  81352. SphericalHarmonics.prototype.scale = function (scale) {
  81353. this.L00 = this.L00.scale(scale);
  81354. this.L1_1 = this.L1_1.scale(scale);
  81355. this.L10 = this.L10.scale(scale);
  81356. this.L11 = this.L11.scale(scale);
  81357. this.L2_2 = this.L2_2.scale(scale);
  81358. this.L2_1 = this.L2_1.scale(scale);
  81359. this.L20 = this.L20.scale(scale);
  81360. this.L21 = this.L21.scale(scale);
  81361. this.L22 = this.L22.scale(scale);
  81362. };
  81363. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81364. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81365. //
  81366. // E_lm = A_l * L_lm
  81367. //
  81368. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81369. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81370. // the scaling factors are given in equation 9.
  81371. // Constant (Band 0)
  81372. this.L00 = this.L00.scale(3.141593);
  81373. // Linear (Band 1)
  81374. this.L1_1 = this.L1_1.scale(2.094395);
  81375. this.L10 = this.L10.scale(2.094395);
  81376. this.L11 = this.L11.scale(2.094395);
  81377. // Quadratic (Band 2)
  81378. this.L2_2 = this.L2_2.scale(0.785398);
  81379. this.L2_1 = this.L2_1.scale(0.785398);
  81380. this.L20 = this.L20.scale(0.785398);
  81381. this.L21 = this.L21.scale(0.785398);
  81382. this.L22 = this.L22.scale(0.785398);
  81383. };
  81384. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81385. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81386. // L = (1/pi) * E * rho
  81387. //
  81388. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81389. this.scale(1.0 / Math.PI);
  81390. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81391. // (The pixel shader must apply albedo after texture fetches, etc).
  81392. };
  81393. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81394. var result = new SphericalHarmonics();
  81395. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81396. result.L1_1 = polynomial.y.scale(0.977204);
  81397. result.L10 = polynomial.z.scale(0.977204);
  81398. result.L11 = polynomial.x.scale(0.977204);
  81399. result.L2_2 = polynomial.xy.scale(1.16538);
  81400. result.L2_1 = polynomial.yz.scale(1.16538);
  81401. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81402. result.L21 = polynomial.zx.scale(1.16538);
  81403. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81404. result.scale(Math.PI);
  81405. return result;
  81406. };
  81407. return SphericalHarmonics;
  81408. }());
  81409. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81410. })(BABYLON || (BABYLON = {}));
  81411. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81412. var BABYLON;
  81413. (function (BABYLON) {
  81414. var FileFaceOrientation = /** @class */ (function () {
  81415. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81416. this.name = name;
  81417. this.worldAxisForNormal = worldAxisForNormal;
  81418. this.worldAxisForFileX = worldAxisForFileX;
  81419. this.worldAxisForFileY = worldAxisForFileY;
  81420. }
  81421. return FileFaceOrientation;
  81422. }());
  81423. ;
  81424. /**
  81425. * Helper class dealing with the extraction of spherical polynomial dataArray
  81426. * from a cube map.
  81427. */
  81428. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81429. function CubeMapToSphericalPolynomialTools() {
  81430. }
  81431. /**
  81432. * Converts a texture to the according Spherical Polynomial data.
  81433. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81434. *
  81435. * @param texture The texture to extract the information from.
  81436. * @return The Spherical Polynomial data.
  81437. */
  81438. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81439. if (!texture.isCube) {
  81440. // Only supports cube Textures currently.
  81441. return null;
  81442. }
  81443. var size = texture.getSize().width;
  81444. var right = texture.readPixels(0);
  81445. var left = texture.readPixels(1);
  81446. var up;
  81447. var down;
  81448. if (texture.isRenderTarget) {
  81449. up = texture.readPixels(3);
  81450. down = texture.readPixels(2);
  81451. }
  81452. else {
  81453. up = texture.readPixels(2);
  81454. down = texture.readPixels(3);
  81455. }
  81456. var front = texture.readPixels(4);
  81457. var back = texture.readPixels(5);
  81458. var gammaSpace = texture.gammaSpace;
  81459. // Always read as RGBA.
  81460. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81461. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81462. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81463. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81464. }
  81465. var cubeInfo = {
  81466. size: size,
  81467. right: right,
  81468. left: left,
  81469. up: up,
  81470. down: down,
  81471. front: front,
  81472. back: back,
  81473. format: format,
  81474. type: type,
  81475. gammaSpace: gammaSpace,
  81476. };
  81477. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81478. };
  81479. /**
  81480. * Converts a cubemap to the according Spherical Polynomial data.
  81481. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81482. *
  81483. * @param cubeInfo The Cube map to extract the information from.
  81484. * @return The Spherical Polynomial data.
  81485. */
  81486. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81487. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81488. var totalSolidAngle = 0.0;
  81489. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81490. var du = 2.0 / cubeInfo.size;
  81491. var dv = du;
  81492. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81493. var minUV = du * 0.5 - 1.0;
  81494. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81495. var fileFace = this.FileFaces[faceIndex];
  81496. var dataArray = cubeInfo[fileFace.name];
  81497. var v = minUV;
  81498. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81499. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81500. // Because SP is still linear, so summation is fine in that basis.
  81501. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81502. for (var y = 0; y < cubeInfo.size; y++) {
  81503. var u = minUV;
  81504. for (var x = 0; x < cubeInfo.size; x++) {
  81505. // World direction (not normalised)
  81506. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81507. worldDirection.normalize();
  81508. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81509. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81510. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81511. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81512. // Handle Integer types.
  81513. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81514. r /= 255;
  81515. g /= 255;
  81516. b /= 255;
  81517. }
  81518. // Handle Gamma space textures.
  81519. if (cubeInfo.gammaSpace) {
  81520. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81521. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81522. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81523. }
  81524. var color = new BABYLON.Color3(r, g, b);
  81525. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81526. totalSolidAngle += deltaSolidAngle;
  81527. u += du;
  81528. }
  81529. v += dv;
  81530. }
  81531. }
  81532. // Solid angle for entire sphere is 4*pi
  81533. var sphereSolidAngle = 4.0 * Math.PI;
  81534. // Adjust the solid angle to allow for how many faces we processed.
  81535. var facesProcessed = 6.0;
  81536. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81537. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81538. // This is needed because the numerical integration over the cube uses a
  81539. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81540. // and also to compensate for accumulative error due to float precision in the summation.
  81541. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81542. sphericalHarmonics.scale(correctionFactor);
  81543. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81544. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81545. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81546. };
  81547. CubeMapToSphericalPolynomialTools.FileFaces = [
  81548. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81549. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81550. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81551. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81552. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81553. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81554. ];
  81555. return CubeMapToSphericalPolynomialTools;
  81556. }());
  81557. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81558. })(BABYLON || (BABYLON = {}));
  81559. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81560. var BABYLON;
  81561. (function (BABYLON) {
  81562. /**
  81563. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81564. */
  81565. var PanoramaToCubeMapTools = /** @class */ (function () {
  81566. function PanoramaToCubeMapTools() {
  81567. }
  81568. /**
  81569. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81570. *
  81571. * @param float32Array The source data.
  81572. * @param inputWidth The width of the input panorama.
  81573. * @param inputhHeight The height of the input panorama.
  81574. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81575. * @return The cubemap data
  81576. */
  81577. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81578. if (!float32Array) {
  81579. throw "ConvertPanoramaToCubemap: input cannot be null";
  81580. }
  81581. if (float32Array.length != inputWidth * inputHeight * 3) {
  81582. throw "ConvertPanoramaToCubemap: input size is wrong";
  81583. }
  81584. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81585. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81586. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81587. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81588. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81589. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81590. return {
  81591. front: textureFront,
  81592. back: textureBack,
  81593. left: textureLeft,
  81594. right: textureRight,
  81595. up: textureUp,
  81596. down: textureDown,
  81597. size: size,
  81598. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81599. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81600. gammaSpace: false,
  81601. };
  81602. };
  81603. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81604. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81605. var textureArray = new Float32Array(buffer);
  81606. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81607. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81608. var dy = 1 / texSize;
  81609. var fy = 0;
  81610. for (var y = 0; y < texSize; y++) {
  81611. var xv1 = faceData[0];
  81612. var xv2 = faceData[2];
  81613. for (var x = 0; x < texSize; x++) {
  81614. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81615. v.normalize();
  81616. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81617. // 3 channels per pixels
  81618. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81619. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81620. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81621. xv1 = xv1.add(rotDX1);
  81622. xv2 = xv2.add(rotDX2);
  81623. }
  81624. fy += dy;
  81625. }
  81626. return textureArray;
  81627. };
  81628. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81629. var theta = Math.atan2(vDir.z, vDir.x);
  81630. var phi = Math.acos(vDir.y);
  81631. while (theta < -Math.PI)
  81632. theta += 2 * Math.PI;
  81633. while (theta > Math.PI)
  81634. theta -= 2 * Math.PI;
  81635. var dx = theta / Math.PI;
  81636. var dy = phi / Math.PI;
  81637. // recenter.
  81638. dx = dx * 0.5 + 0.5;
  81639. var px = Math.round(dx * inputWidth);
  81640. if (px < 0)
  81641. px = 0;
  81642. else if (px >= inputWidth)
  81643. px = inputWidth - 1;
  81644. var py = Math.round(dy * inputHeight);
  81645. if (py < 0)
  81646. py = 0;
  81647. else if (py >= inputHeight)
  81648. py = inputHeight - 1;
  81649. var inputY = (inputHeight - py - 1);
  81650. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81651. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81652. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81653. return {
  81654. r: r,
  81655. g: g,
  81656. b: b
  81657. };
  81658. };
  81659. PanoramaToCubeMapTools.FACE_FRONT = [
  81660. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81661. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81662. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81663. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81664. ];
  81665. PanoramaToCubeMapTools.FACE_BACK = [
  81666. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81667. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81668. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81669. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81670. ];
  81671. PanoramaToCubeMapTools.FACE_RIGHT = [
  81672. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81673. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81674. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81675. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81676. ];
  81677. PanoramaToCubeMapTools.FACE_LEFT = [
  81678. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81679. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81680. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81681. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81682. ];
  81683. PanoramaToCubeMapTools.FACE_DOWN = [
  81684. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81685. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81686. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81687. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81688. ];
  81689. PanoramaToCubeMapTools.FACE_UP = [
  81690. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81691. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81692. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81693. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81694. ];
  81695. return PanoramaToCubeMapTools;
  81696. }());
  81697. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81698. })(BABYLON || (BABYLON = {}));
  81699. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81700. var BABYLON;
  81701. (function (BABYLON) {
  81702. ;
  81703. /**
  81704. * This groups tools to convert HDR texture to native colors array.
  81705. */
  81706. var HDRTools = /** @class */ (function () {
  81707. function HDRTools() {
  81708. }
  81709. HDRTools.Ldexp = function (mantissa, exponent) {
  81710. if (exponent > 1023) {
  81711. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81712. }
  81713. if (exponent < -1074) {
  81714. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81715. }
  81716. return mantissa * Math.pow(2, exponent);
  81717. };
  81718. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81719. if (exponent > 0) { /*nonzero pixel*/
  81720. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81721. float32array[index + 0] = red * exponent;
  81722. float32array[index + 1] = green * exponent;
  81723. float32array[index + 2] = blue * exponent;
  81724. }
  81725. else {
  81726. float32array[index + 0] = 0;
  81727. float32array[index + 1] = 0;
  81728. float32array[index + 2] = 0;
  81729. }
  81730. };
  81731. HDRTools.readStringLine = function (uint8array, startIndex) {
  81732. var line = "";
  81733. var character = "";
  81734. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81735. character = String.fromCharCode(uint8array[i]);
  81736. if (character == "\n") {
  81737. break;
  81738. }
  81739. line += character;
  81740. }
  81741. return line;
  81742. };
  81743. /**
  81744. * Reads header information from an RGBE texture stored in a native array.
  81745. * More information on this format are available here:
  81746. * https://en.wikipedia.org/wiki/RGBE_image_format
  81747. *
  81748. * @param uint8array The binary file stored in native array.
  81749. * @return The header information.
  81750. */
  81751. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81752. var height = 0;
  81753. var width = 0;
  81754. var line = this.readStringLine(uint8array, 0);
  81755. if (line[0] != '#' || line[1] != '?') {
  81756. throw "Bad HDR Format.";
  81757. }
  81758. var endOfHeader = false;
  81759. var findFormat = false;
  81760. var lineIndex = 0;
  81761. do {
  81762. lineIndex += (line.length + 1);
  81763. line = this.readStringLine(uint8array, lineIndex);
  81764. if (line == "FORMAT=32-bit_rle_rgbe") {
  81765. findFormat = true;
  81766. }
  81767. else if (line.length == 0) {
  81768. endOfHeader = true;
  81769. }
  81770. } while (!endOfHeader);
  81771. if (!findFormat) {
  81772. throw "HDR Bad header format, unsupported FORMAT";
  81773. }
  81774. lineIndex += (line.length + 1);
  81775. line = this.readStringLine(uint8array, lineIndex);
  81776. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81777. var match = sizeRegexp.exec(line);
  81778. // TODO. Support +Y and -X if needed.
  81779. if (!match || match.length < 3) {
  81780. throw "HDR Bad header format, no size";
  81781. }
  81782. width = parseInt(match[2]);
  81783. height = parseInt(match[1]);
  81784. if (width < 8 || width > 0x7fff) {
  81785. throw "HDR Bad header format, unsupported size";
  81786. }
  81787. lineIndex += (line.length + 1);
  81788. return {
  81789. height: height,
  81790. width: width,
  81791. dataPosition: lineIndex
  81792. };
  81793. };
  81794. /**
  81795. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81796. * This RGBE texture needs to store the information as a panorama.
  81797. *
  81798. * More information on this format are available here:
  81799. * https://en.wikipedia.org/wiki/RGBE_image_format
  81800. *
  81801. * @param buffer The binary file stored in an array buffer.
  81802. * @param size The expected size of the extracted cubemap.
  81803. * @return The Cube Map information.
  81804. */
  81805. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81806. var uint8array = new Uint8Array(buffer);
  81807. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81808. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81809. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81810. return cubeMapData;
  81811. };
  81812. /**
  81813. * Returns the pixels data extracted from an RGBE texture.
  81814. * This pixels will be stored left to right up to down in the R G B order in one array.
  81815. *
  81816. * More information on this format are available here:
  81817. * https://en.wikipedia.org/wiki/RGBE_image_format
  81818. *
  81819. * @param uint8array The binary file stored in an array buffer.
  81820. * @param hdrInfo The header information of the file.
  81821. * @return The pixels data in RGB right to left up to down order.
  81822. */
  81823. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81824. // Keep for multi format supports.
  81825. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81826. };
  81827. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81828. var num_scanlines = hdrInfo.height;
  81829. var scanline_width = hdrInfo.width;
  81830. var a, b, c, d, count;
  81831. var dataIndex = hdrInfo.dataPosition;
  81832. var index = 0, endIndex = 0, i = 0;
  81833. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81834. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81835. // 3 channels of 4 bytes per pixel in float.
  81836. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81837. var resultArray = new Float32Array(resultBuffer);
  81838. // read in each successive scanline
  81839. while (num_scanlines > 0) {
  81840. a = uint8array[dataIndex++];
  81841. b = uint8array[dataIndex++];
  81842. c = uint8array[dataIndex++];
  81843. d = uint8array[dataIndex++];
  81844. if (a != 2 || b != 2 || (c & 0x80)) {
  81845. // this file is not run length encoded
  81846. throw "HDR Bad header format, not RLE";
  81847. }
  81848. if (((c << 8) | d) != scanline_width) {
  81849. throw "HDR Bad header format, wrong scan line width";
  81850. }
  81851. index = 0;
  81852. // read each of the four channels for the scanline into the buffer
  81853. for (i = 0; i < 4; i++) {
  81854. endIndex = (i + 1) * scanline_width;
  81855. while (index < endIndex) {
  81856. a = uint8array[dataIndex++];
  81857. b = uint8array[dataIndex++];
  81858. if (a > 128) {
  81859. // a run of the same value
  81860. count = a - 128;
  81861. if ((count == 0) || (count > endIndex - index)) {
  81862. throw "HDR Bad Format, bad scanline data (run)";
  81863. }
  81864. while (count-- > 0) {
  81865. scanLineArray[index++] = b;
  81866. }
  81867. }
  81868. else {
  81869. // a non-run
  81870. count = a;
  81871. if ((count == 0) || (count > endIndex - index)) {
  81872. throw "HDR Bad Format, bad scanline data (non-run)";
  81873. }
  81874. scanLineArray[index++] = b;
  81875. if (--count > 0) {
  81876. for (var j = 0; j < count; j++) {
  81877. scanLineArray[index++] = uint8array[dataIndex++];
  81878. }
  81879. }
  81880. }
  81881. }
  81882. }
  81883. // now convert data from buffer into floats
  81884. for (i = 0; i < scanline_width; i++) {
  81885. a = scanLineArray[i];
  81886. b = scanLineArray[i + scanline_width];
  81887. c = scanLineArray[i + 2 * scanline_width];
  81888. d = scanLineArray[i + 3 * scanline_width];
  81889. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81890. }
  81891. num_scanlines--;
  81892. }
  81893. return resultArray;
  81894. };
  81895. return HDRTools;
  81896. }());
  81897. BABYLON.HDRTools = HDRTools;
  81898. })(BABYLON || (BABYLON = {}));
  81899. //# sourceMappingURL=babylon.hdr.js.map
  81900. var BABYLON;
  81901. (function (BABYLON) {
  81902. /**
  81903. * Sets of helpers addressing the serialization and deserialization of environment texture
  81904. * stored in a BabylonJS env file.
  81905. * Those files are usually stored as .env files.
  81906. */
  81907. var EnvironmentTextureTools = /** @class */ (function () {
  81908. function EnvironmentTextureTools() {
  81909. }
  81910. /**
  81911. * Gets the environment info from an env file.
  81912. * @param data The array buffer containing the .env bytes.
  81913. * @returns the environment file info (the json header) if successfully parsed.
  81914. */
  81915. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81916. var dataView = new DataView(data);
  81917. var pos = 0;
  81918. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81919. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81920. BABYLON.Tools.Error('Not a babylon environment map');
  81921. return null;
  81922. }
  81923. }
  81924. // Read json manifest - collect characters up to null terminator
  81925. var manifestString = '';
  81926. var charCode = 0x00;
  81927. while ((charCode = dataView.getUint8(pos++))) {
  81928. manifestString += String.fromCharCode(charCode);
  81929. }
  81930. var manifest = JSON.parse(manifestString);
  81931. if (manifest.specular) {
  81932. // Extend the header with the position of the payload.
  81933. manifest.specular.specularDataPosition = pos;
  81934. }
  81935. return manifest;
  81936. };
  81937. /**
  81938. * Creates an environment texture from a loaded cube texture.
  81939. * @param texture defines the cube texture to convert in env file
  81940. * @return a promise containing the environment data if succesfull.
  81941. */
  81942. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81943. var _this = this;
  81944. var internalTexture = texture.getInternalTexture();
  81945. if (!internalTexture) {
  81946. return Promise.reject("The cube texture is invalid.");
  81947. }
  81948. if (!texture._prefiltered) {
  81949. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81950. }
  81951. var engine = internalTexture.getEngine();
  81952. if (engine && engine.premultipliedAlpha) {
  81953. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81954. }
  81955. var canvas = engine.getRenderingCanvas();
  81956. if (!canvas) {
  81957. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81958. }
  81959. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81960. if (!engine.getCaps().textureFloatRender) {
  81961. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81962. if (!engine.getCaps().textureHalfFloatRender) {
  81963. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81964. }
  81965. }
  81966. var cubeWidth = internalTexture.width;
  81967. var hostingScene = new BABYLON.Scene(engine);
  81968. var specularTextures = {};
  81969. var promises = [];
  81970. // Read and collect all mipmaps data from the cube.
  81971. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81972. mipmapsCount = Math.round(mipmapsCount);
  81973. var _loop_1 = function (i) {
  81974. var faceWidth = Math.pow(2, mipmapsCount - i);
  81975. var _loop_2 = function (face) {
  81976. var data = texture.readPixels(face, i);
  81977. // Creates a temp texture with the face data.
  81978. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81979. // And rgbdEncode them.
  81980. var promise = new Promise(function (resolve, reject) {
  81981. 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);
  81982. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81983. rgbdPostProcess.onApply = function (effect) {
  81984. effect._bindTexture("textureSampler", tempTexture);
  81985. };
  81986. // As the process needs to happen on the main canvas, keep track of the current size
  81987. var currentW = engine.getRenderWidth();
  81988. var currentH = engine.getRenderHeight();
  81989. // Set the desired size for the texture
  81990. engine.setSize(faceWidth, faceWidth);
  81991. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81992. // Reading datas from WebGL
  81993. canvas.toBlob(function (blob) {
  81994. var fileReader = new FileReader();
  81995. fileReader.onload = function (event) {
  81996. var arrayBuffer = event.target.result;
  81997. specularTextures[i * 6 + face] = arrayBuffer;
  81998. resolve();
  81999. };
  82000. fileReader.readAsArrayBuffer(blob);
  82001. });
  82002. // Reapply the previous canvas size
  82003. engine.setSize(currentW, currentH);
  82004. });
  82005. });
  82006. promises.push(promise);
  82007. };
  82008. // All faces of the cube.
  82009. for (var face = 0; face < 6; face++) {
  82010. _loop_2(face);
  82011. }
  82012. };
  82013. for (var i = 0; i <= mipmapsCount; i++) {
  82014. _loop_1(i);
  82015. }
  82016. // Once all the textures haves been collected as RGBD stored in PNGs
  82017. return Promise.all(promises).then(function () {
  82018. // We can delete the hosting scene keeping track of all the creation objects
  82019. hostingScene.dispose();
  82020. // Creates the json header for the env texture
  82021. var info = {
  82022. version: 1,
  82023. width: cubeWidth,
  82024. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82025. specular: {
  82026. mipmaps: []
  82027. }
  82028. };
  82029. // Sets the specular image data information
  82030. var position = 0;
  82031. for (var i = 0; i <= mipmapsCount; i++) {
  82032. for (var face = 0; face < 6; face++) {
  82033. var byteLength = specularTextures[i * 6 + face].byteLength;
  82034. info.specular.mipmaps.push({
  82035. length: byteLength,
  82036. position: position
  82037. });
  82038. position += byteLength;
  82039. }
  82040. }
  82041. // Encode the JSON as an array buffer
  82042. var infoString = JSON.stringify(info);
  82043. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82044. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82045. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82046. infoView[i] = infoString.charCodeAt(i);
  82047. }
  82048. // Ends up with a null terminator for easier parsing
  82049. infoView[infoString.length] = 0x00;
  82050. // Computes the final required size and creates the storage
  82051. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82052. var finalBuffer = new ArrayBuffer(totalSize);
  82053. var finalBufferView = new Uint8Array(finalBuffer);
  82054. var dataView = new DataView(finalBuffer);
  82055. // Copy the magic bytes identifying the file in
  82056. var pos = 0;
  82057. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82058. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82059. }
  82060. // Add the json info
  82061. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82062. pos += infoBuffer.byteLength;
  82063. // Finally inserts the texture data
  82064. for (var i = 0; i <= mipmapsCount; i++) {
  82065. for (var face = 0; face < 6; face++) {
  82066. var dataBuffer = specularTextures[i * 6 + face];
  82067. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82068. pos += dataBuffer.byteLength;
  82069. }
  82070. }
  82071. // Voila
  82072. return finalBuffer;
  82073. });
  82074. };
  82075. /**
  82076. * Creates a JSON representation of the spherical data.
  82077. * @param texture defines the texture containing the polynomials
  82078. * @return the JSON representation of the spherical info
  82079. */
  82080. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82081. var polynmials = texture.sphericalPolynomial;
  82082. if (polynmials == null) {
  82083. return null;
  82084. }
  82085. return {
  82086. polynomials: true,
  82087. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82088. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82089. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82090. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82091. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82092. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82093. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82094. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82095. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82096. };
  82097. };
  82098. /**
  82099. * Uploads the texture info contained in the env file to te GPU.
  82100. * @param texture defines the internal texture to upload to
  82101. * @param arrayBuffer defines the buffer cotaining the data to load
  82102. * @param info defines the texture info retrieved through the GetEnvInfo method
  82103. * @returns a promise
  82104. */
  82105. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82106. if (info.version !== 1) {
  82107. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82108. }
  82109. var specularInfo = info.specular;
  82110. if (!specularInfo) {
  82111. // Nothing else parsed so far
  82112. return Promise.resolve();
  82113. }
  82114. // Double checks the enclosed info
  82115. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82116. mipmapsCount = Math.round(mipmapsCount) + 1;
  82117. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82118. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82119. }
  82120. // Gets everything ready.
  82121. var engine = texture.getEngine();
  82122. var expandTexture = false;
  82123. var generateNonLODTextures = false;
  82124. var rgbdPostProcess = null;
  82125. var cubeRtt = null;
  82126. var lodTextures = null;
  82127. var caps = engine.getCaps();
  82128. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82129. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82130. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82131. // Add extra process if texture lod is not supported
  82132. if (!caps.textureLOD) {
  82133. expandTexture = false;
  82134. generateNonLODTextures = true;
  82135. lodTextures = {};
  82136. }
  82137. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82138. else if (engine.webGLVersion < 2) {
  82139. expandTexture = false;
  82140. }
  82141. // If half float available we can uncompress the texture
  82142. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82143. expandTexture = true;
  82144. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82145. }
  82146. // If full float available we can uncompress the texture
  82147. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82148. expandTexture = true;
  82149. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82150. }
  82151. // Expand the texture if possible
  82152. if (expandTexture) {
  82153. // Simply run through the decode PP
  82154. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82155. texture._isRGBD = false;
  82156. texture.invertY = false;
  82157. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82158. generateDepthBuffer: false,
  82159. generateMipMaps: true,
  82160. generateStencilBuffer: false,
  82161. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82162. type: texture.type,
  82163. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82164. });
  82165. }
  82166. else {
  82167. texture._isRGBD = true;
  82168. texture.invertY = true;
  82169. // In case of missing support, applies the same patch than DDS files.
  82170. if (generateNonLODTextures) {
  82171. var mipSlices = 3;
  82172. var scale = texture._lodGenerationScale;
  82173. var offset = texture._lodGenerationOffset;
  82174. for (var i = 0; i < mipSlices; i++) {
  82175. //compute LOD from even spacing in smoothness (matching shader calculation)
  82176. var smoothness = i / (mipSlices - 1);
  82177. var roughness = 1 - smoothness;
  82178. var minLODIndex = offset; // roughness = 0
  82179. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82180. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82181. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82182. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82183. glTextureFromLod.isCube = true;
  82184. glTextureFromLod.invertY = true;
  82185. glTextureFromLod.generateMipMaps = false;
  82186. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82187. // Wrap in a base texture for easy binding.
  82188. var lodTexture = new BABYLON.BaseTexture(null);
  82189. lodTexture.isCube = true;
  82190. lodTexture._texture = glTextureFromLod;
  82191. lodTextures[mipmapIndex] = lodTexture;
  82192. switch (i) {
  82193. case 0:
  82194. texture._lodTextureLow = lodTexture;
  82195. break;
  82196. case 1:
  82197. texture._lodTextureMid = lodTexture;
  82198. break;
  82199. case 2:
  82200. texture._lodTextureHigh = lodTexture;
  82201. break;
  82202. }
  82203. }
  82204. }
  82205. }
  82206. var promises = [];
  82207. var _loop_3 = function (i) {
  82208. var _loop_4 = function (face) {
  82209. // Retrieves the face data
  82210. var imageData = specularInfo.mipmaps[i * 6 + face];
  82211. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82212. // Constructs an image element from bytes
  82213. var blob = new Blob([bytes], { type: 'image/png' });
  82214. var url = URL.createObjectURL(blob);
  82215. var image = new Image();
  82216. image.src = url;
  82217. // Enqueue promise to upload to the texture.
  82218. var promise = new Promise(function (resolve, reject) {
  82219. ;
  82220. image.onload = function () {
  82221. if (expandTexture) {
  82222. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82223. reject(message);
  82224. }, image);
  82225. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82226. // Uncompress the data to a RTT
  82227. rgbdPostProcess.onApply = function (effect) {
  82228. effect._bindTexture("textureSampler", tempTexture_1);
  82229. effect.setFloat2("scale", 1, 1);
  82230. };
  82231. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82232. // Cleanup
  82233. engine.restoreDefaultFramebuffer();
  82234. tempTexture_1.dispose();
  82235. window.URL.revokeObjectURL(url);
  82236. resolve();
  82237. });
  82238. }
  82239. else {
  82240. engine._uploadImageToTexture(texture, face, i, image);
  82241. // Upload the face to the none lod texture support
  82242. if (generateNonLODTextures) {
  82243. var lodTexture = lodTextures[i];
  82244. if (lodTexture) {
  82245. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82246. }
  82247. }
  82248. resolve();
  82249. }
  82250. };
  82251. image.onerror = function (error) {
  82252. reject(error);
  82253. };
  82254. });
  82255. promises.push(promise);
  82256. };
  82257. // All faces
  82258. for (var face = 0; face < 6; face++) {
  82259. _loop_4(face);
  82260. }
  82261. };
  82262. // All mipmaps
  82263. for (var i = 0; i < mipmapsCount; i++) {
  82264. _loop_3(i);
  82265. }
  82266. // Once all done, finishes the cleanup and return
  82267. return Promise.all(promises).then(function () {
  82268. // Relase temp RTT.
  82269. if (cubeRtt) {
  82270. engine._releaseFramebufferObjects(cubeRtt);
  82271. cubeRtt._swapAndDie(texture);
  82272. }
  82273. // Relase temp Post Process.
  82274. if (rgbdPostProcess) {
  82275. rgbdPostProcess.dispose();
  82276. }
  82277. // Flag internal texture as ready in case they are in use.
  82278. if (generateNonLODTextures) {
  82279. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82280. texture._lodTextureHigh._texture.isReady = true;
  82281. }
  82282. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82283. texture._lodTextureMid._texture.isReady = true;
  82284. }
  82285. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82286. texture._lodTextureLow._texture.isReady = true;
  82287. }
  82288. }
  82289. });
  82290. };
  82291. /**
  82292. * Uploads spherical polynomials information to the texture.
  82293. * @param texture defines the texture we are trying to upload the information to
  82294. * @param arrayBuffer defines the array buffer holding the data
  82295. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82296. */
  82297. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82298. if (info.version !== 1) {
  82299. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82300. }
  82301. var irradianceInfo = info.irradiance;
  82302. if (!irradianceInfo) {
  82303. return;
  82304. }
  82305. //harmonics now represent radiance
  82306. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82307. if (irradianceInfo.polynomials) {
  82308. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82309. }
  82310. else {
  82311. // convert From SH to SP.
  82312. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82313. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82314. }
  82315. };
  82316. /**
  82317. * Upload spherical polynomial coefficients to the texture
  82318. * @param polynmials Spherical polynmial coefficients (9)
  82319. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82320. */
  82321. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82322. outPolynomialCoefficents.x.x = polynmials.x[0];
  82323. outPolynomialCoefficents.x.y = polynmials.x[1];
  82324. outPolynomialCoefficents.x.z = polynmials.x[2];
  82325. outPolynomialCoefficents.y.x = polynmials.y[0];
  82326. outPolynomialCoefficents.y.y = polynmials.y[1];
  82327. outPolynomialCoefficents.y.z = polynmials.y[2];
  82328. outPolynomialCoefficents.z.x = polynmials.z[0];
  82329. outPolynomialCoefficents.z.y = polynmials.z[1];
  82330. outPolynomialCoefficents.z.z = polynmials.z[2];
  82331. //xx
  82332. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82333. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82334. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82335. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82336. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82337. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82338. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82339. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82340. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82341. //yz
  82342. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82343. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82344. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82345. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82346. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82347. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82348. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82349. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82350. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82351. };
  82352. /**
  82353. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82354. * L = (1/pi) * E * rho
  82355. *
  82356. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82357. * @param harmonics Spherical harmonic coefficients (9)
  82358. */
  82359. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82360. var scaleFactor = 1 / Math.PI;
  82361. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82362. // (The pixel shader must apply albedo after texture fetches, etc).
  82363. harmonics.l00[0] *= scaleFactor;
  82364. harmonics.l00[1] *= scaleFactor;
  82365. harmonics.l00[2] *= scaleFactor;
  82366. harmonics.l1_1[0] *= scaleFactor;
  82367. harmonics.l1_1[1] *= scaleFactor;
  82368. harmonics.l1_1[2] *= scaleFactor;
  82369. harmonics.l10[0] *= scaleFactor;
  82370. harmonics.l10[1] *= scaleFactor;
  82371. harmonics.l10[2] *= scaleFactor;
  82372. harmonics.l11[0] *= scaleFactor;
  82373. harmonics.l11[1] *= scaleFactor;
  82374. harmonics.l11[2] *= scaleFactor;
  82375. harmonics.l2_2[0] *= scaleFactor;
  82376. harmonics.l2_2[1] *= scaleFactor;
  82377. harmonics.l2_2[2] *= scaleFactor;
  82378. harmonics.l2_1[0] *= scaleFactor;
  82379. harmonics.l2_1[1] *= scaleFactor;
  82380. harmonics.l2_1[2] *= scaleFactor;
  82381. harmonics.l20[0] *= scaleFactor;
  82382. harmonics.l20[1] *= scaleFactor;
  82383. harmonics.l20[2] *= scaleFactor;
  82384. harmonics.l21[0] *= scaleFactor;
  82385. harmonics.l21[1] *= scaleFactor;
  82386. harmonics.l21[2] *= scaleFactor;
  82387. harmonics.l22[0] *= scaleFactor;
  82388. harmonics.l22[1] *= scaleFactor;
  82389. harmonics.l22[2] *= scaleFactor;
  82390. };
  82391. /**
  82392. * Convert spherical harmonics to spherical polynomial coefficients
  82393. * @param harmonics Spherical harmonic coefficients (9)
  82394. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82395. */
  82396. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82397. var rPi = 1 / Math.PI;
  82398. //x
  82399. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82400. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82401. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82402. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82403. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82404. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82405. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82406. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82407. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82408. //xx
  82409. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82410. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82411. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82412. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82413. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82414. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82415. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82416. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82417. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82418. //yz
  82419. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82420. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82421. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82422. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82423. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82424. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82425. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82426. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82427. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82428. };
  82429. /**
  82430. * Magic number identifying the env file.
  82431. */
  82432. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82433. return EnvironmentTextureTools;
  82434. }());
  82435. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82436. })(BABYLON || (BABYLON = {}));
  82437. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82438. var BABYLON;
  82439. (function (BABYLON) {
  82440. /**
  82441. * This represents a texture coming from an HDR input.
  82442. *
  82443. * The only supported format is currently panorama picture stored in RGBE format.
  82444. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82445. */
  82446. var HDRCubeTexture = /** @class */ (function (_super) {
  82447. __extends(HDRCubeTexture, _super);
  82448. /**
  82449. * Instantiates an HDRTexture from the following parameters.
  82450. *
  82451. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82452. * @param scene The scene the texture will be used in
  82453. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82454. * @param noMipmap Forces to not generate the mipmap if true
  82455. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82456. * @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)
  82457. * @param reserved Reserved flag for internal use.
  82458. */
  82459. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82460. if (noMipmap === void 0) { noMipmap = false; }
  82461. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82462. if (gammaSpace === void 0) { gammaSpace = false; }
  82463. if (reserved === void 0) { reserved = false; }
  82464. if (onLoad === void 0) { onLoad = null; }
  82465. if (onError === void 0) { onError = null; }
  82466. var _this = _super.call(this, scene) || this;
  82467. _this._generateHarmonics = true;
  82468. _this._onLoad = null;
  82469. _this._onError = null;
  82470. /**
  82471. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82472. */
  82473. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82474. _this._isBlocking = true;
  82475. _this._rotationY = 0;
  82476. /**
  82477. * Gets or sets the center of the bounding box associated with the cube texture
  82478. * It must define where the camera used to render the texture was set
  82479. */
  82480. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82481. if (!url) {
  82482. return _this;
  82483. }
  82484. _this.name = url;
  82485. _this.url = url;
  82486. _this.hasAlpha = false;
  82487. _this.isCube = true;
  82488. _this._textureMatrix = BABYLON.Matrix.Identity();
  82489. _this._onLoad = onLoad;
  82490. _this._onError = onError;
  82491. _this.gammaSpace = gammaSpace;
  82492. _this._noMipmap = noMipmap;
  82493. _this._size = size;
  82494. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82495. if (!_this._texture) {
  82496. if (!scene.useDelayedTextureLoading) {
  82497. _this.loadTexture();
  82498. }
  82499. else {
  82500. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82501. }
  82502. }
  82503. return _this;
  82504. }
  82505. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82506. /**
  82507. * Gets wether or not the texture is blocking during loading.
  82508. */
  82509. get: function () {
  82510. return this._isBlocking;
  82511. },
  82512. /**
  82513. * Sets wether or not the texture is blocking during loading.
  82514. */
  82515. set: function (value) {
  82516. this._isBlocking = value;
  82517. },
  82518. enumerable: true,
  82519. configurable: true
  82520. });
  82521. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82522. /**
  82523. * Gets texture matrix rotation angle around Y axis radians.
  82524. */
  82525. get: function () {
  82526. return this._rotationY;
  82527. },
  82528. /**
  82529. * Sets texture matrix rotation angle around Y axis in radians.
  82530. */
  82531. set: function (value) {
  82532. this._rotationY = value;
  82533. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82534. },
  82535. enumerable: true,
  82536. configurable: true
  82537. });
  82538. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82539. get: function () {
  82540. return this._boundingBoxSize;
  82541. },
  82542. /**
  82543. * Gets or sets the size of the bounding box associated with the cube texture
  82544. * When defined, the cubemap will switch to local mode
  82545. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82546. * @example https://www.babylonjs-playground.com/#RNASML
  82547. */
  82548. set: function (value) {
  82549. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82550. return;
  82551. }
  82552. this._boundingBoxSize = value;
  82553. var scene = this.getScene();
  82554. if (scene) {
  82555. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82556. }
  82557. },
  82558. enumerable: true,
  82559. configurable: true
  82560. });
  82561. /**
  82562. * Occurs when the file is raw .hdr file.
  82563. */
  82564. HDRCubeTexture.prototype.loadTexture = function () {
  82565. var _this = this;
  82566. var callback = function (buffer) {
  82567. _this.lodGenerationOffset = 0.0;
  82568. _this.lodGenerationScale = 0.8;
  82569. var scene = _this.getScene();
  82570. if (!scene) {
  82571. return null;
  82572. }
  82573. // Extract the raw linear data.
  82574. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82575. // Generate harmonics if needed.
  82576. if (_this._generateHarmonics) {
  82577. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82578. _this.sphericalPolynomial = sphericalPolynomial;
  82579. }
  82580. var results = [];
  82581. var byteArray = null;
  82582. // Push each faces.
  82583. for (var j = 0; j < 6; j++) {
  82584. // Create uintarray fallback.
  82585. if (!scene.getEngine().getCaps().textureFloat) {
  82586. // 3 channels of 1 bytes per pixel in bytes.
  82587. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82588. byteArray = new Uint8Array(byteBuffer);
  82589. }
  82590. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82591. // If special cases.
  82592. if (_this.gammaSpace || byteArray) {
  82593. for (var i = 0; i < _this._size * _this._size; i++) {
  82594. // Put in gamma space if requested.
  82595. if (_this.gammaSpace) {
  82596. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82597. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82598. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82599. }
  82600. // Convert to int texture for fallback.
  82601. if (byteArray) {
  82602. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82603. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82604. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82605. // May use luminance instead if the result is not accurate.
  82606. var max = Math.max(Math.max(r, g), b);
  82607. if (max > 255) {
  82608. var scale = 255 / max;
  82609. r *= scale;
  82610. g *= scale;
  82611. b *= scale;
  82612. }
  82613. byteArray[(i * 3) + 0] = r;
  82614. byteArray[(i * 3) + 1] = g;
  82615. byteArray[(i * 3) + 2] = b;
  82616. }
  82617. }
  82618. }
  82619. if (byteArray) {
  82620. results.push(byteArray);
  82621. }
  82622. else {
  82623. results.push(dataFace);
  82624. }
  82625. }
  82626. return results;
  82627. };
  82628. var scene = this.getScene();
  82629. if (scene) {
  82630. 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);
  82631. }
  82632. };
  82633. HDRCubeTexture.prototype.clone = function () {
  82634. var scene = this.getScene();
  82635. if (!scene) {
  82636. return this;
  82637. }
  82638. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82639. // Base texture
  82640. newTexture.level = this.level;
  82641. newTexture.wrapU = this.wrapU;
  82642. newTexture.wrapV = this.wrapV;
  82643. newTexture.coordinatesIndex = this.coordinatesIndex;
  82644. newTexture.coordinatesMode = this.coordinatesMode;
  82645. return newTexture;
  82646. };
  82647. // Methods
  82648. HDRCubeTexture.prototype.delayLoad = function () {
  82649. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82650. return;
  82651. }
  82652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82653. this._texture = this._getFromCache(this.url, this._noMipmap);
  82654. if (!this._texture) {
  82655. this.loadTexture();
  82656. }
  82657. };
  82658. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82659. return this._textureMatrix;
  82660. };
  82661. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82662. this._textureMatrix = value;
  82663. };
  82664. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82665. var texture = null;
  82666. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82667. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82668. texture.name = parsedTexture.name;
  82669. texture.hasAlpha = parsedTexture.hasAlpha;
  82670. texture.level = parsedTexture.level;
  82671. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82672. texture.isBlocking = parsedTexture.isBlocking;
  82673. }
  82674. if (texture) {
  82675. if (parsedTexture.boundingBoxPosition) {
  82676. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82677. }
  82678. if (parsedTexture.boundingBoxSize) {
  82679. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82680. }
  82681. if (parsedTexture.rotationY) {
  82682. texture.rotationY = parsedTexture.rotationY;
  82683. }
  82684. }
  82685. return texture;
  82686. };
  82687. HDRCubeTexture.prototype.serialize = function () {
  82688. if (!this.name) {
  82689. return null;
  82690. }
  82691. var serializationObject = {};
  82692. serializationObject.name = this.name;
  82693. serializationObject.hasAlpha = this.hasAlpha;
  82694. serializationObject.isCube = true;
  82695. serializationObject.level = this.level;
  82696. serializationObject.size = this._size;
  82697. serializationObject.coordinatesMode = this.coordinatesMode;
  82698. serializationObject.useInGammaSpace = this.gammaSpace;
  82699. serializationObject.generateHarmonics = this._generateHarmonics;
  82700. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82701. serializationObject.noMipmap = this._noMipmap;
  82702. serializationObject.isBlocking = this._isBlocking;
  82703. serializationObject.rotationY = this._rotationY;
  82704. return serializationObject;
  82705. };
  82706. HDRCubeTexture._facesMapping = [
  82707. "right",
  82708. "left",
  82709. "up",
  82710. "down",
  82711. "front",
  82712. "back"
  82713. ];
  82714. return HDRCubeTexture;
  82715. }(BABYLON.BaseTexture));
  82716. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82717. })(BABYLON || (BABYLON = {}));
  82718. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82719. var BABYLON;
  82720. (function (BABYLON) {
  82721. var IndexedVector2 = /** @class */ (function (_super) {
  82722. __extends(IndexedVector2, _super);
  82723. function IndexedVector2(original, index) {
  82724. var _this = _super.call(this, original.x, original.y) || this;
  82725. _this.index = index;
  82726. return _this;
  82727. }
  82728. return IndexedVector2;
  82729. }(BABYLON.Vector2));
  82730. var PolygonPoints = /** @class */ (function () {
  82731. function PolygonPoints() {
  82732. this.elements = new Array();
  82733. }
  82734. PolygonPoints.prototype.add = function (originalPoints) {
  82735. var _this = this;
  82736. var result = new Array();
  82737. originalPoints.forEach(function (point) {
  82738. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82739. var newPoint = new IndexedVector2(point, _this.elements.length);
  82740. result.push(newPoint);
  82741. _this.elements.push(newPoint);
  82742. }
  82743. });
  82744. return result;
  82745. };
  82746. PolygonPoints.prototype.computeBounds = function () {
  82747. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82748. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82749. this.elements.forEach(function (point) {
  82750. // x
  82751. if (point.x < lmin.x) {
  82752. lmin.x = point.x;
  82753. }
  82754. else if (point.x > lmax.x) {
  82755. lmax.x = point.x;
  82756. }
  82757. // y
  82758. if (point.y < lmin.y) {
  82759. lmin.y = point.y;
  82760. }
  82761. else if (point.y > lmax.y) {
  82762. lmax.y = point.y;
  82763. }
  82764. });
  82765. return {
  82766. min: lmin,
  82767. max: lmax,
  82768. width: lmax.x - lmin.x,
  82769. height: lmax.y - lmin.y
  82770. };
  82771. };
  82772. return PolygonPoints;
  82773. }());
  82774. var Polygon = /** @class */ (function () {
  82775. function Polygon() {
  82776. }
  82777. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82778. return [
  82779. new BABYLON.Vector2(xmin, ymin),
  82780. new BABYLON.Vector2(xmax, ymin),
  82781. new BABYLON.Vector2(xmax, ymax),
  82782. new BABYLON.Vector2(xmin, ymax)
  82783. ];
  82784. };
  82785. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82786. if (cx === void 0) { cx = 0; }
  82787. if (cy === void 0) { cy = 0; }
  82788. if (numberOfSides === void 0) { numberOfSides = 32; }
  82789. var result = new Array();
  82790. var angle = 0;
  82791. var increment = (Math.PI * 2) / numberOfSides;
  82792. for (var i = 0; i < numberOfSides; i++) {
  82793. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82794. angle -= increment;
  82795. }
  82796. return result;
  82797. };
  82798. Polygon.Parse = function (input) {
  82799. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82800. var i, result = [];
  82801. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82802. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82803. }
  82804. return result;
  82805. };
  82806. Polygon.StartingAt = function (x, y) {
  82807. return BABYLON.Path2.StartingAt(x, y);
  82808. };
  82809. return Polygon;
  82810. }());
  82811. BABYLON.Polygon = Polygon;
  82812. var PolygonMeshBuilder = /** @class */ (function () {
  82813. function PolygonMeshBuilder(name, contours, scene) {
  82814. this._points = new PolygonPoints();
  82815. this._outlinepoints = new PolygonPoints();
  82816. this._holes = new Array();
  82817. this._epoints = new Array();
  82818. this._eholes = new Array();
  82819. this._name = name;
  82820. this._scene = scene;
  82821. var points;
  82822. if (contours instanceof BABYLON.Path2) {
  82823. points = contours.getPoints();
  82824. }
  82825. else {
  82826. points = contours;
  82827. }
  82828. this._addToepoint(points);
  82829. this._points.add(points);
  82830. this._outlinepoints.add(points);
  82831. if (typeof earcut === 'undefined') {
  82832. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82833. }
  82834. }
  82835. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82836. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82837. var p = points_1[_i];
  82838. this._epoints.push(p.x, p.y);
  82839. }
  82840. };
  82841. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82842. this._points.add(hole);
  82843. var holepoints = new PolygonPoints();
  82844. holepoints.add(hole);
  82845. this._holes.push(holepoints);
  82846. this._eholes.push(this._epoints.length / 2);
  82847. this._addToepoint(hole);
  82848. return this;
  82849. };
  82850. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82851. var _this = this;
  82852. if (updatable === void 0) { updatable = false; }
  82853. if (depth === void 0) { depth = 0; }
  82854. var result = new BABYLON.Mesh(this._name, this._scene);
  82855. var normals = new Array();
  82856. var positions = new Array();
  82857. var uvs = new Array();
  82858. var bounds = this._points.computeBounds();
  82859. this._points.elements.forEach(function (p) {
  82860. normals.push(0, 1.0, 0);
  82861. positions.push(p.x, 0, p.y);
  82862. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82863. });
  82864. var indices = new Array();
  82865. var res = earcut(this._epoints, this._eholes, 2);
  82866. for (var i = 0; i < res.length; i++) {
  82867. indices.push(res[i]);
  82868. }
  82869. if (depth > 0) {
  82870. var positionscount = (positions.length / 3); //get the current pointcount
  82871. this._points.elements.forEach(function (p) {
  82872. normals.push(0, -1.0, 0);
  82873. positions.push(p.x, -depth, p.y);
  82874. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82875. });
  82876. var totalCount = indices.length;
  82877. for (var i = 0; i < totalCount; i += 3) {
  82878. var i0 = indices[i + 0];
  82879. var i1 = indices[i + 1];
  82880. var i2 = indices[i + 2];
  82881. indices.push(i2 + positionscount);
  82882. indices.push(i1 + positionscount);
  82883. indices.push(i0 + positionscount);
  82884. }
  82885. //Add the sides
  82886. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82887. this._holes.forEach(function (hole) {
  82888. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82889. });
  82890. }
  82891. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82892. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82893. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82894. result.setIndices(indices);
  82895. return result;
  82896. };
  82897. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82898. var StartIndex = positions.length / 3;
  82899. var ulength = 0;
  82900. for (var i = 0; i < points.elements.length; i++) {
  82901. var p = points.elements[i];
  82902. var p1;
  82903. if ((i + 1) > points.elements.length - 1) {
  82904. p1 = points.elements[0];
  82905. }
  82906. else {
  82907. p1 = points.elements[i + 1];
  82908. }
  82909. positions.push(p.x, 0, p.y);
  82910. positions.push(p.x, -depth, p.y);
  82911. positions.push(p1.x, 0, p1.y);
  82912. positions.push(p1.x, -depth, p1.y);
  82913. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82914. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82915. var v3 = v2.subtract(v1);
  82916. var v4 = new BABYLON.Vector3(0, 1, 0);
  82917. var vn = BABYLON.Vector3.Cross(v3, v4);
  82918. vn = vn.normalize();
  82919. uvs.push(ulength / bounds.width, 0);
  82920. uvs.push(ulength / bounds.width, 1);
  82921. ulength += v3.length();
  82922. uvs.push((ulength / bounds.width), 0);
  82923. uvs.push((ulength / bounds.width), 1);
  82924. if (!flip) {
  82925. normals.push(-vn.x, -vn.y, -vn.z);
  82926. normals.push(-vn.x, -vn.y, -vn.z);
  82927. normals.push(-vn.x, -vn.y, -vn.z);
  82928. normals.push(-vn.x, -vn.y, -vn.z);
  82929. indices.push(StartIndex);
  82930. indices.push(StartIndex + 1);
  82931. indices.push(StartIndex + 2);
  82932. indices.push(StartIndex + 1);
  82933. indices.push(StartIndex + 3);
  82934. indices.push(StartIndex + 2);
  82935. }
  82936. else {
  82937. normals.push(vn.x, vn.y, vn.z);
  82938. normals.push(vn.x, vn.y, vn.z);
  82939. normals.push(vn.x, vn.y, vn.z);
  82940. normals.push(vn.x, vn.y, vn.z);
  82941. indices.push(StartIndex);
  82942. indices.push(StartIndex + 2);
  82943. indices.push(StartIndex + 1);
  82944. indices.push(StartIndex + 1);
  82945. indices.push(StartIndex + 2);
  82946. indices.push(StartIndex + 3);
  82947. }
  82948. StartIndex += 4;
  82949. }
  82950. ;
  82951. };
  82952. return PolygonMeshBuilder;
  82953. }());
  82954. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82955. })(BABYLON || (BABYLON = {}));
  82956. //# sourceMappingURL=babylon.polygonMesh.js.map
  82957. var BABYLON;
  82958. (function (BABYLON) {
  82959. // Unique ID when we import meshes from Babylon to CSG
  82960. var currentCSGMeshId = 0;
  82961. // # class Vertex
  82962. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82963. // one to provide additional features like texture coordinates and vertex
  82964. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82965. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82966. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82967. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82968. // is not used anywhere else.
  82969. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82970. var Vertex = /** @class */ (function () {
  82971. function Vertex(pos, normal, uv) {
  82972. this.pos = pos;
  82973. this.normal = normal;
  82974. this.uv = uv;
  82975. }
  82976. Vertex.prototype.clone = function () {
  82977. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82978. };
  82979. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82980. // orientation of a polygon is flipped.
  82981. Vertex.prototype.flip = function () {
  82982. this.normal = this.normal.scale(-1);
  82983. };
  82984. // Create a new vertex between this vertex and `other` by linearly
  82985. // interpolating all properties using a parameter of `t`. Subclasses should
  82986. // override this to interpolate additional properties.
  82987. Vertex.prototype.interpolate = function (other, t) {
  82988. 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));
  82989. };
  82990. return Vertex;
  82991. }());
  82992. // # class Plane
  82993. // Represents a plane in 3D space.
  82994. var Plane = /** @class */ (function () {
  82995. function Plane(normal, w) {
  82996. this.normal = normal;
  82997. this.w = w;
  82998. }
  82999. Plane.FromPoints = function (a, b, c) {
  83000. var v0 = c.subtract(a);
  83001. var v1 = b.subtract(a);
  83002. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83003. return null;
  83004. }
  83005. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83006. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83007. };
  83008. Plane.prototype.clone = function () {
  83009. return new Plane(this.normal.clone(), this.w);
  83010. };
  83011. Plane.prototype.flip = function () {
  83012. this.normal.scaleInPlace(-1);
  83013. this.w = -this.w;
  83014. };
  83015. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83016. // fragments in the appropriate lists. Coplanar polygons go into either
  83017. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83018. // respect to this plane. Polygons in front or in back of this plane go into
  83019. // either `front` or `back`.
  83020. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83021. var COPLANAR = 0;
  83022. var FRONT = 1;
  83023. var BACK = 2;
  83024. var SPANNING = 3;
  83025. // Classify each point as well as the entire polygon into one of the above
  83026. // four classes.
  83027. var polygonType = 0;
  83028. var types = [];
  83029. var i;
  83030. var t;
  83031. for (i = 0; i < polygon.vertices.length; i++) {
  83032. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83033. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83034. polygonType |= type;
  83035. types.push(type);
  83036. }
  83037. // Put the polygon in the correct list, splitting it when necessary.
  83038. switch (polygonType) {
  83039. case COPLANAR:
  83040. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83041. break;
  83042. case FRONT:
  83043. front.push(polygon);
  83044. break;
  83045. case BACK:
  83046. back.push(polygon);
  83047. break;
  83048. case SPANNING:
  83049. var f = [], b = [];
  83050. for (i = 0; i < polygon.vertices.length; i++) {
  83051. var j = (i + 1) % polygon.vertices.length;
  83052. var ti = types[i], tj = types[j];
  83053. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83054. if (ti !== BACK)
  83055. f.push(vi);
  83056. if (ti !== FRONT)
  83057. b.push(ti !== BACK ? vi.clone() : vi);
  83058. if ((ti | tj) === SPANNING) {
  83059. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83060. var v = vi.interpolate(vj, t);
  83061. f.push(v);
  83062. b.push(v.clone());
  83063. }
  83064. }
  83065. var poly;
  83066. if (f.length >= 3) {
  83067. poly = new Polygon(f, polygon.shared);
  83068. if (poly.plane)
  83069. front.push(poly);
  83070. }
  83071. if (b.length >= 3) {
  83072. poly = new Polygon(b, polygon.shared);
  83073. if (poly.plane)
  83074. back.push(poly);
  83075. }
  83076. break;
  83077. }
  83078. };
  83079. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83080. // point is on the plane.
  83081. Plane.EPSILON = 1e-5;
  83082. return Plane;
  83083. }());
  83084. // # class Polygon
  83085. // Represents a convex polygon. The vertices used to initialize a polygon must
  83086. // be coplanar and form a convex loop.
  83087. //
  83088. // Each convex polygon has a `shared` property, which is shared between all
  83089. // polygons that are clones of each other or were split from the same polygon.
  83090. // This can be used to define per-polygon properties (such as surface color).
  83091. var Polygon = /** @class */ (function () {
  83092. function Polygon(vertices, shared) {
  83093. this.vertices = vertices;
  83094. this.shared = shared;
  83095. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83096. }
  83097. Polygon.prototype.clone = function () {
  83098. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83099. return new Polygon(vertices, this.shared);
  83100. };
  83101. Polygon.prototype.flip = function () {
  83102. this.vertices.reverse().map(function (v) { v.flip(); });
  83103. this.plane.flip();
  83104. };
  83105. return Polygon;
  83106. }());
  83107. // # class Node
  83108. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83109. // by picking a polygon to split along. That polygon (and all other coplanar
  83110. // polygons) are added directly to that node and the other polygons are added to
  83111. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83112. // no distinction between internal and leaf nodes.
  83113. var Node = /** @class */ (function () {
  83114. function Node(polygons) {
  83115. this.plane = null;
  83116. this.front = null;
  83117. this.back = null;
  83118. this.polygons = new Array();
  83119. if (polygons) {
  83120. this.build(polygons);
  83121. }
  83122. }
  83123. Node.prototype.clone = function () {
  83124. var node = new Node();
  83125. node.plane = this.plane && this.plane.clone();
  83126. node.front = this.front && this.front.clone();
  83127. node.back = this.back && this.back.clone();
  83128. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83129. return node;
  83130. };
  83131. // Convert solid space to empty space and empty space to solid space.
  83132. Node.prototype.invert = function () {
  83133. for (var i = 0; i < this.polygons.length; i++) {
  83134. this.polygons[i].flip();
  83135. }
  83136. if (this.plane) {
  83137. this.plane.flip();
  83138. }
  83139. if (this.front) {
  83140. this.front.invert();
  83141. }
  83142. if (this.back) {
  83143. this.back.invert();
  83144. }
  83145. var temp = this.front;
  83146. this.front = this.back;
  83147. this.back = temp;
  83148. };
  83149. // Recursively remove all polygons in `polygons` that are inside this BSP
  83150. // tree.
  83151. Node.prototype.clipPolygons = function (polygons) {
  83152. if (!this.plane)
  83153. return polygons.slice();
  83154. var front = new Array(), back = new Array();
  83155. for (var i = 0; i < polygons.length; i++) {
  83156. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83157. }
  83158. if (this.front) {
  83159. front = this.front.clipPolygons(front);
  83160. }
  83161. if (this.back) {
  83162. back = this.back.clipPolygons(back);
  83163. }
  83164. else {
  83165. back = [];
  83166. }
  83167. return front.concat(back);
  83168. };
  83169. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83170. // `bsp`.
  83171. Node.prototype.clipTo = function (bsp) {
  83172. this.polygons = bsp.clipPolygons(this.polygons);
  83173. if (this.front)
  83174. this.front.clipTo(bsp);
  83175. if (this.back)
  83176. this.back.clipTo(bsp);
  83177. };
  83178. // Return a list of all polygons in this BSP tree.
  83179. Node.prototype.allPolygons = function () {
  83180. var polygons = this.polygons.slice();
  83181. if (this.front)
  83182. polygons = polygons.concat(this.front.allPolygons());
  83183. if (this.back)
  83184. polygons = polygons.concat(this.back.allPolygons());
  83185. return polygons;
  83186. };
  83187. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83188. // new polygons are filtered down to the bottom of the tree and become new
  83189. // nodes there. Each set of polygons is partitioned using the first polygon
  83190. // (no heuristic is used to pick a good split).
  83191. Node.prototype.build = function (polygons) {
  83192. if (!polygons.length)
  83193. return;
  83194. if (!this.plane)
  83195. this.plane = polygons[0].plane.clone();
  83196. var front = new Array(), back = new Array();
  83197. for (var i = 0; i < polygons.length; i++) {
  83198. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83199. }
  83200. if (front.length) {
  83201. if (!this.front)
  83202. this.front = new Node();
  83203. this.front.build(front);
  83204. }
  83205. if (back.length) {
  83206. if (!this.back)
  83207. this.back = new Node();
  83208. this.back.build(back);
  83209. }
  83210. };
  83211. return Node;
  83212. }());
  83213. var CSG = /** @class */ (function () {
  83214. function CSG() {
  83215. this.polygons = new Array();
  83216. }
  83217. // Convert BABYLON.Mesh to BABYLON.CSG
  83218. CSG.FromMesh = function (mesh) {
  83219. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83220. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83221. if (mesh instanceof BABYLON.Mesh) {
  83222. mesh.computeWorldMatrix(true);
  83223. matrix = mesh.getWorldMatrix();
  83224. meshPosition = mesh.position.clone();
  83225. meshRotation = mesh.rotation.clone();
  83226. if (mesh.rotationQuaternion) {
  83227. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83228. }
  83229. meshScaling = mesh.scaling.clone();
  83230. }
  83231. else {
  83232. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83233. }
  83234. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83235. var subMeshes = mesh.subMeshes;
  83236. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83237. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83238. vertices = [];
  83239. for (var j = 0; j < 3; j++) {
  83240. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83241. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83242. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83243. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83244. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83245. vertex = new Vertex(position, normal, uv);
  83246. vertices.push(vertex);
  83247. }
  83248. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83249. // To handle the case of degenerated triangle
  83250. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83251. if (polygon.plane)
  83252. polygons.push(polygon);
  83253. }
  83254. }
  83255. var csg = CSG.FromPolygons(polygons);
  83256. csg.matrix = matrix;
  83257. csg.position = meshPosition;
  83258. csg.rotation = meshRotation;
  83259. csg.scaling = meshScaling;
  83260. csg.rotationQuaternion = meshRotationQuaternion;
  83261. currentCSGMeshId++;
  83262. return csg;
  83263. };
  83264. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83265. CSG.FromPolygons = function (polygons) {
  83266. var csg = new CSG();
  83267. csg.polygons = polygons;
  83268. return csg;
  83269. };
  83270. CSG.prototype.clone = function () {
  83271. var csg = new CSG();
  83272. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83273. csg.copyTransformAttributes(this);
  83274. return csg;
  83275. };
  83276. CSG.prototype.union = function (csg) {
  83277. var a = new Node(this.clone().polygons);
  83278. var b = new Node(csg.clone().polygons);
  83279. a.clipTo(b);
  83280. b.clipTo(a);
  83281. b.invert();
  83282. b.clipTo(a);
  83283. b.invert();
  83284. a.build(b.allPolygons());
  83285. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83286. };
  83287. CSG.prototype.unionInPlace = function (csg) {
  83288. var a = new Node(this.polygons);
  83289. var b = new Node(csg.polygons);
  83290. a.clipTo(b);
  83291. b.clipTo(a);
  83292. b.invert();
  83293. b.clipTo(a);
  83294. b.invert();
  83295. a.build(b.allPolygons());
  83296. this.polygons = a.allPolygons();
  83297. };
  83298. CSG.prototype.subtract = function (csg) {
  83299. var a = new Node(this.clone().polygons);
  83300. var b = new Node(csg.clone().polygons);
  83301. a.invert();
  83302. a.clipTo(b);
  83303. b.clipTo(a);
  83304. b.invert();
  83305. b.clipTo(a);
  83306. b.invert();
  83307. a.build(b.allPolygons());
  83308. a.invert();
  83309. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83310. };
  83311. CSG.prototype.subtractInPlace = function (csg) {
  83312. var a = new Node(this.polygons);
  83313. var b = new Node(csg.polygons);
  83314. a.invert();
  83315. a.clipTo(b);
  83316. b.clipTo(a);
  83317. b.invert();
  83318. b.clipTo(a);
  83319. b.invert();
  83320. a.build(b.allPolygons());
  83321. a.invert();
  83322. this.polygons = a.allPolygons();
  83323. };
  83324. CSG.prototype.intersect = function (csg) {
  83325. var a = new Node(this.clone().polygons);
  83326. var b = new Node(csg.clone().polygons);
  83327. a.invert();
  83328. b.clipTo(a);
  83329. b.invert();
  83330. a.clipTo(b);
  83331. b.clipTo(a);
  83332. a.build(b.allPolygons());
  83333. a.invert();
  83334. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83335. };
  83336. CSG.prototype.intersectInPlace = function (csg) {
  83337. var a = new Node(this.polygons);
  83338. var b = new Node(csg.polygons);
  83339. a.invert();
  83340. b.clipTo(a);
  83341. b.invert();
  83342. a.clipTo(b);
  83343. b.clipTo(a);
  83344. a.build(b.allPolygons());
  83345. a.invert();
  83346. this.polygons = a.allPolygons();
  83347. };
  83348. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83349. // not modified.
  83350. CSG.prototype.inverse = function () {
  83351. var csg = this.clone();
  83352. csg.inverseInPlace();
  83353. return csg;
  83354. };
  83355. CSG.prototype.inverseInPlace = function () {
  83356. this.polygons.map(function (p) { p.flip(); });
  83357. };
  83358. // This is used to keep meshes transformations so they can be restored
  83359. // when we build back a Babylon Mesh
  83360. // NB : All CSG operations are performed in world coordinates
  83361. CSG.prototype.copyTransformAttributes = function (csg) {
  83362. this.matrix = csg.matrix;
  83363. this.position = csg.position;
  83364. this.rotation = csg.rotation;
  83365. this.scaling = csg.scaling;
  83366. this.rotationQuaternion = csg.rotationQuaternion;
  83367. return this;
  83368. };
  83369. // Build Raw mesh from CSG
  83370. // Coordinates here are in world space
  83371. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83372. var matrix = this.matrix.clone();
  83373. matrix.invert();
  83374. 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;
  83375. if (keepSubMeshes) {
  83376. // Sort Polygons, since subMeshes are indices range
  83377. polygons.sort(function (a, b) {
  83378. if (a.shared.meshId === b.shared.meshId) {
  83379. return a.shared.subMeshId - b.shared.subMeshId;
  83380. }
  83381. else {
  83382. return a.shared.meshId - b.shared.meshId;
  83383. }
  83384. });
  83385. }
  83386. for (var i = 0, il = polygons.length; i < il; i++) {
  83387. polygon = polygons[i];
  83388. // Building SubMeshes
  83389. if (!subMesh_dict[polygon.shared.meshId]) {
  83390. subMesh_dict[polygon.shared.meshId] = {};
  83391. }
  83392. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83393. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83394. indexStart: +Infinity,
  83395. indexEnd: -Infinity,
  83396. materialIndex: polygon.shared.materialIndex
  83397. };
  83398. }
  83399. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83400. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83401. polygonIndices[0] = 0;
  83402. polygonIndices[1] = j - 1;
  83403. polygonIndices[2] = j;
  83404. for (var k = 0; k < 3; k++) {
  83405. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83406. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83407. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83408. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83409. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83410. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83411. // Check if 2 points can be merged
  83412. if (!(typeof vertex_idx !== 'undefined' &&
  83413. normals[vertex_idx * 3] === localNormal.x &&
  83414. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83415. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83416. uvs[vertex_idx * 2] === uv.x &&
  83417. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83418. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83419. uvs.push(uv.x, uv.y);
  83420. normals.push(normal.x, normal.y, normal.z);
  83421. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83422. }
  83423. indices.push(vertex_idx);
  83424. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83425. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83426. currentIndex++;
  83427. }
  83428. }
  83429. }
  83430. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83431. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83432. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83433. mesh.setIndices(indices, null);
  83434. if (keepSubMeshes) {
  83435. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83436. var materialIndexOffset = 0, materialMaxIndex;
  83437. mesh.subMeshes = new Array();
  83438. for (var m in subMesh_dict) {
  83439. materialMaxIndex = -1;
  83440. for (var sm in subMesh_dict[m]) {
  83441. subMesh_obj = subMesh_dict[m][sm];
  83442. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83443. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83444. }
  83445. materialIndexOffset += ++materialMaxIndex;
  83446. }
  83447. }
  83448. return mesh;
  83449. };
  83450. // Build Mesh from CSG taking material and transforms into account
  83451. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83452. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83453. mesh.material = material;
  83454. mesh.position.copyFrom(this.position);
  83455. mesh.rotation.copyFrom(this.rotation);
  83456. if (this.rotationQuaternion) {
  83457. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83458. }
  83459. mesh.scaling.copyFrom(this.scaling);
  83460. mesh.computeWorldMatrix(true);
  83461. return mesh;
  83462. };
  83463. return CSG;
  83464. }());
  83465. BABYLON.CSG = CSG;
  83466. })(BABYLON || (BABYLON = {}));
  83467. //# sourceMappingURL=babylon.csg.js.map
  83468. var BABYLON;
  83469. (function (BABYLON) {
  83470. var LensFlare = /** @class */ (function () {
  83471. function LensFlare(size, position, color, imgUrl, system) {
  83472. this.size = size;
  83473. this.position = position;
  83474. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83475. this.color = color || new BABYLON.Color3(1, 1, 1);
  83476. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83477. this._system = system;
  83478. system.lensFlares.push(this);
  83479. }
  83480. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83481. return new LensFlare(size, position, color, imgUrl, system);
  83482. };
  83483. LensFlare.prototype.dispose = function () {
  83484. if (this.texture) {
  83485. this.texture.dispose();
  83486. }
  83487. // Remove from scene
  83488. var index = this._system.lensFlares.indexOf(this);
  83489. this._system.lensFlares.splice(index, 1);
  83490. };
  83491. ;
  83492. return LensFlare;
  83493. }());
  83494. BABYLON.LensFlare = LensFlare;
  83495. })(BABYLON || (BABYLON = {}));
  83496. //# sourceMappingURL=babylon.lensFlare.js.map
  83497. var BABYLON;
  83498. (function (BABYLON) {
  83499. var LensFlareSystem = /** @class */ (function () {
  83500. function LensFlareSystem(name, emitter, scene) {
  83501. this.name = name;
  83502. this.lensFlares = new Array();
  83503. this.borderLimit = 300;
  83504. this.viewportBorder = 0;
  83505. this.layerMask = 0x0FFFFFFF;
  83506. this._vertexBuffers = {};
  83507. this._isEnabled = true;
  83508. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83509. this._emitter = emitter;
  83510. this.id = name;
  83511. scene.lensFlareSystems.push(this);
  83512. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83513. var engine = scene.getEngine();
  83514. // VBO
  83515. var vertices = [];
  83516. vertices.push(1, 1);
  83517. vertices.push(-1, 1);
  83518. vertices.push(-1, -1);
  83519. vertices.push(1, -1);
  83520. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83521. // Indices
  83522. var indices = [];
  83523. indices.push(0);
  83524. indices.push(1);
  83525. indices.push(2);
  83526. indices.push(0);
  83527. indices.push(2);
  83528. indices.push(3);
  83529. this._indexBuffer = engine.createIndexBuffer(indices);
  83530. // Effects
  83531. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83532. }
  83533. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83534. get: function () {
  83535. return this._isEnabled;
  83536. },
  83537. set: function (value) {
  83538. this._isEnabled = value;
  83539. },
  83540. enumerable: true,
  83541. configurable: true
  83542. });
  83543. LensFlareSystem.prototype.getScene = function () {
  83544. return this._scene;
  83545. };
  83546. LensFlareSystem.prototype.getEmitter = function () {
  83547. return this._emitter;
  83548. };
  83549. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83550. this._emitter = newEmitter;
  83551. };
  83552. LensFlareSystem.prototype.getEmitterPosition = function () {
  83553. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83554. };
  83555. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83556. var position = this.getEmitterPosition();
  83557. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83558. this._positionX = position.x;
  83559. this._positionY = position.y;
  83560. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83561. if (this.viewportBorder > 0) {
  83562. globalViewport.x -= this.viewportBorder;
  83563. globalViewport.y -= this.viewportBorder;
  83564. globalViewport.width += this.viewportBorder * 2;
  83565. globalViewport.height += this.viewportBorder * 2;
  83566. position.x += this.viewportBorder;
  83567. position.y += this.viewportBorder;
  83568. this._positionX += this.viewportBorder;
  83569. this._positionY += this.viewportBorder;
  83570. }
  83571. if (position.z > 0) {
  83572. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83573. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83574. return true;
  83575. }
  83576. return true;
  83577. }
  83578. return false;
  83579. };
  83580. LensFlareSystem.prototype._isVisible = function () {
  83581. if (!this._isEnabled || !this._scene.activeCamera) {
  83582. return false;
  83583. }
  83584. var emitterPosition = this.getEmitterPosition();
  83585. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83586. var distance = direction.length();
  83587. direction.normalize();
  83588. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83589. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83590. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83591. };
  83592. LensFlareSystem.prototype.render = function () {
  83593. if (!this._effect.isReady() || !this._scene.activeCamera)
  83594. return false;
  83595. var engine = this._scene.getEngine();
  83596. var viewport = this._scene.activeCamera.viewport;
  83597. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83598. // Position
  83599. if (!this.computeEffectivePosition(globalViewport)) {
  83600. return false;
  83601. }
  83602. // Visibility
  83603. if (!this._isVisible()) {
  83604. return false;
  83605. }
  83606. // Intensity
  83607. var awayX;
  83608. var awayY;
  83609. if (this._positionX < this.borderLimit + globalViewport.x) {
  83610. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83611. }
  83612. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83613. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83614. }
  83615. else {
  83616. awayX = 0;
  83617. }
  83618. if (this._positionY < this.borderLimit + globalViewport.y) {
  83619. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83620. }
  83621. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83622. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83623. }
  83624. else {
  83625. awayY = 0;
  83626. }
  83627. var away = (awayX > awayY) ? awayX : awayY;
  83628. away -= this.viewportBorder;
  83629. if (away > this.borderLimit) {
  83630. away = this.borderLimit;
  83631. }
  83632. var intensity = 1.0 - (away / this.borderLimit);
  83633. if (intensity < 0) {
  83634. return false;
  83635. }
  83636. if (intensity > 1.0) {
  83637. intensity = 1.0;
  83638. }
  83639. if (this.viewportBorder > 0) {
  83640. globalViewport.x += this.viewportBorder;
  83641. globalViewport.y += this.viewportBorder;
  83642. globalViewport.width -= this.viewportBorder * 2;
  83643. globalViewport.height -= this.viewportBorder * 2;
  83644. this._positionX -= this.viewportBorder;
  83645. this._positionY -= this.viewportBorder;
  83646. }
  83647. // Position
  83648. var centerX = globalViewport.x + globalViewport.width / 2;
  83649. var centerY = globalViewport.y + globalViewport.height / 2;
  83650. var distX = centerX - this._positionX;
  83651. var distY = centerY - this._positionY;
  83652. // Effects
  83653. engine.enableEffect(this._effect);
  83654. engine.setState(false);
  83655. engine.setDepthBuffer(false);
  83656. // VBOs
  83657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83658. // Flares
  83659. for (var index = 0; index < this.lensFlares.length; index++) {
  83660. var flare = this.lensFlares[index];
  83661. engine.setAlphaMode(flare.alphaMode);
  83662. var x = centerX - (distX * flare.position);
  83663. var y = centerY - (distY * flare.position);
  83664. var cw = flare.size;
  83665. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83666. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83667. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83668. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83669. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83670. // Texture
  83671. this._effect.setTexture("textureSampler", flare.texture);
  83672. // Color
  83673. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83674. // Draw order
  83675. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83676. }
  83677. engine.setDepthBuffer(true);
  83678. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83679. return true;
  83680. };
  83681. LensFlareSystem.prototype.dispose = function () {
  83682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83683. if (vertexBuffer) {
  83684. vertexBuffer.dispose();
  83685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83686. }
  83687. if (this._indexBuffer) {
  83688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83689. this._indexBuffer = null;
  83690. }
  83691. while (this.lensFlares.length) {
  83692. this.lensFlares[0].dispose();
  83693. }
  83694. // Remove from scene
  83695. var index = this._scene.lensFlareSystems.indexOf(this);
  83696. this._scene.lensFlareSystems.splice(index, 1);
  83697. };
  83698. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83699. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83700. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83701. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83702. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83703. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83704. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83705. var parsedFlare = parsedLensFlareSystem.flares[index];
  83706. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83707. }
  83708. return lensFlareSystem;
  83709. };
  83710. LensFlareSystem.prototype.serialize = function () {
  83711. var serializationObject = {};
  83712. serializationObject.id = this.id;
  83713. serializationObject.name = this.name;
  83714. serializationObject.emitterId = this.getEmitter().id;
  83715. serializationObject.borderLimit = this.borderLimit;
  83716. serializationObject.flares = [];
  83717. for (var index = 0; index < this.lensFlares.length; index++) {
  83718. var flare = this.lensFlares[index];
  83719. serializationObject.flares.push({
  83720. size: flare.size,
  83721. position: flare.position,
  83722. color: flare.color.asArray(),
  83723. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83724. });
  83725. }
  83726. return serializationObject;
  83727. };
  83728. return LensFlareSystem;
  83729. }());
  83730. BABYLON.LensFlareSystem = LensFlareSystem;
  83731. })(BABYLON || (BABYLON = {}));
  83732. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83733. var BABYLON;
  83734. (function (BABYLON) {
  83735. /**
  83736. * This is a holder class for the physics joint created by the physics plugin.
  83737. * It holds a set of functions to control the underlying joint.
  83738. */
  83739. var PhysicsJoint = /** @class */ (function () {
  83740. function PhysicsJoint(type, jointData) {
  83741. this.type = type;
  83742. this.jointData = jointData;
  83743. jointData.nativeParams = jointData.nativeParams || {};
  83744. }
  83745. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83746. get: function () {
  83747. return this._physicsJoint;
  83748. },
  83749. set: function (newJoint) {
  83750. if (this._physicsJoint) {
  83751. //remove from the wolrd
  83752. }
  83753. this._physicsJoint = newJoint;
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83759. set: function (physicsPlugin) {
  83760. this._physicsPlugin = physicsPlugin;
  83761. },
  83762. enumerable: true,
  83763. configurable: true
  83764. });
  83765. /**
  83766. * Execute a function that is physics-plugin specific.
  83767. * @param {Function} func the function that will be executed.
  83768. * It accepts two parameters: the physics world and the physics joint.
  83769. */
  83770. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83771. func(this._physicsPlugin.world, this._physicsJoint);
  83772. };
  83773. //TODO check if the native joints are the same
  83774. //Joint Types
  83775. PhysicsJoint.DistanceJoint = 0;
  83776. PhysicsJoint.HingeJoint = 1;
  83777. PhysicsJoint.BallAndSocketJoint = 2;
  83778. PhysicsJoint.WheelJoint = 3;
  83779. PhysicsJoint.SliderJoint = 4;
  83780. //OIMO
  83781. PhysicsJoint.PrismaticJoint = 5;
  83782. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83783. PhysicsJoint.UniversalJoint = 6;
  83784. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83785. //Cannon
  83786. //Similar to a Ball-Joint. Different in params
  83787. PhysicsJoint.PointToPointJoint = 8;
  83788. //Cannon only at the moment
  83789. PhysicsJoint.SpringJoint = 9;
  83790. PhysicsJoint.LockJoint = 10;
  83791. return PhysicsJoint;
  83792. }());
  83793. BABYLON.PhysicsJoint = PhysicsJoint;
  83794. /**
  83795. * A class representing a physics distance joint.
  83796. */
  83797. var DistanceJoint = /** @class */ (function (_super) {
  83798. __extends(DistanceJoint, _super);
  83799. function DistanceJoint(jointData) {
  83800. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83801. }
  83802. /**
  83803. * Update the predefined distance.
  83804. */
  83805. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83806. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83807. };
  83808. return DistanceJoint;
  83809. }(PhysicsJoint));
  83810. BABYLON.DistanceJoint = DistanceJoint;
  83811. var MotorEnabledJoint = /** @class */ (function (_super) {
  83812. __extends(MotorEnabledJoint, _super);
  83813. function MotorEnabledJoint(type, jointData) {
  83814. return _super.call(this, type, jointData) || this;
  83815. }
  83816. /**
  83817. * Set the motor values.
  83818. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83819. * @param {number} force the force to apply
  83820. * @param {number} maxForce max force for this motor.
  83821. */
  83822. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83823. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83824. };
  83825. /**
  83826. * Set the motor's limits.
  83827. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83828. */
  83829. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83830. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83831. };
  83832. return MotorEnabledJoint;
  83833. }(PhysicsJoint));
  83834. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83835. /**
  83836. * This class represents a single hinge physics joint
  83837. */
  83838. var HingeJoint = /** @class */ (function (_super) {
  83839. __extends(HingeJoint, _super);
  83840. function HingeJoint(jointData) {
  83841. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83842. }
  83843. /**
  83844. * Set the motor values.
  83845. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83846. * @param {number} force the force to apply
  83847. * @param {number} maxForce max force for this motor.
  83848. */
  83849. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83850. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83851. };
  83852. /**
  83853. * Set the motor's limits.
  83854. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83855. */
  83856. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83857. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83858. };
  83859. return HingeJoint;
  83860. }(MotorEnabledJoint));
  83861. BABYLON.HingeJoint = HingeJoint;
  83862. /**
  83863. * This class represents a dual hinge physics joint (same as wheel joint)
  83864. */
  83865. var Hinge2Joint = /** @class */ (function (_super) {
  83866. __extends(Hinge2Joint, _super);
  83867. function Hinge2Joint(jointData) {
  83868. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83869. }
  83870. /**
  83871. * Set the motor values.
  83872. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83873. * @param {number} force the force to apply
  83874. * @param {number} maxForce max force for this motor.
  83875. * @param {motorIndex} the motor's index, 0 or 1.
  83876. */
  83877. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83878. if (motorIndex === void 0) { motorIndex = 0; }
  83879. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83880. };
  83881. /**
  83882. * Set the motor limits.
  83883. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83884. * @param {number} upperLimit the upper limit
  83885. * @param {number} lowerLimit lower limit
  83886. * @param {motorIndex} the motor's index, 0 or 1.
  83887. */
  83888. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83889. if (motorIndex === void 0) { motorIndex = 0; }
  83890. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83891. };
  83892. return Hinge2Joint;
  83893. }(MotorEnabledJoint));
  83894. BABYLON.Hinge2Joint = Hinge2Joint;
  83895. })(BABYLON || (BABYLON = {}));
  83896. //# sourceMappingURL=babylon.physicsJoint.js.map
  83897. var BABYLON;
  83898. (function (BABYLON) {
  83899. var PhysicsImpostor = /** @class */ (function () {
  83900. function PhysicsImpostor(object, type, _options, _scene) {
  83901. if (_options === void 0) { _options = { mass: 0 }; }
  83902. var _this = this;
  83903. this.object = object;
  83904. this.type = type;
  83905. this._options = _options;
  83906. this._scene = _scene;
  83907. this._bodyUpdateRequired = false;
  83908. this._onBeforePhysicsStepCallbacks = new Array();
  83909. this._onAfterPhysicsStepCallbacks = new Array();
  83910. this._onPhysicsCollideCallbacks = [];
  83911. this._deltaPosition = BABYLON.Vector3.Zero();
  83912. this._isDisposed = false;
  83913. //temp variables for parent rotation calculations
  83914. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83915. this._tmpQuat = new BABYLON.Quaternion();
  83916. this._tmpQuat2 = new BABYLON.Quaternion();
  83917. /**
  83918. * this function is executed by the physics engine.
  83919. */
  83920. this.beforeStep = function () {
  83921. if (!_this._physicsEngine) {
  83922. return;
  83923. }
  83924. _this.object.translate(_this._deltaPosition, -1);
  83925. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83926. _this.object.computeWorldMatrix(false);
  83927. if (_this.object.parent && _this.object.rotationQuaternion) {
  83928. _this.getParentsRotation();
  83929. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83930. }
  83931. else {
  83932. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83933. }
  83934. if (!_this._options.disableBidirectionalTransformation) {
  83935. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83936. }
  83937. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83938. func(_this);
  83939. });
  83940. };
  83941. /**
  83942. * this function is executed by the physics engine.
  83943. */
  83944. this.afterStep = function () {
  83945. if (!_this._physicsEngine) {
  83946. return;
  83947. }
  83948. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83949. func(_this);
  83950. });
  83951. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83952. // object has now its world rotation. needs to be converted to local.
  83953. if (_this.object.parent && _this.object.rotationQuaternion) {
  83954. _this.getParentsRotation();
  83955. _this._tmpQuat.conjugateInPlace();
  83956. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83957. }
  83958. // take the position set and make it the absolute position of this object.
  83959. _this.object.setAbsolutePosition(_this.object.position);
  83960. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83961. _this.object.translate(_this._deltaPosition, 1);
  83962. };
  83963. /**
  83964. * Legacy collision detection event support
  83965. */
  83966. this.onCollideEvent = null;
  83967. //event and body object due to cannon's event-based architecture.
  83968. this.onCollide = function (e) {
  83969. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83970. return;
  83971. }
  83972. if (!_this._physicsEngine) {
  83973. return;
  83974. }
  83975. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83976. if (otherImpostor) {
  83977. // Legacy collision detection event support
  83978. if (_this.onCollideEvent) {
  83979. _this.onCollideEvent(_this, otherImpostor);
  83980. }
  83981. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83982. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83983. }).forEach(function (obj) {
  83984. obj.callback(_this, otherImpostor);
  83985. });
  83986. }
  83987. };
  83988. //sanity check!
  83989. if (!this.object) {
  83990. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83991. return;
  83992. }
  83993. //legacy support for old syntax.
  83994. if (!this._scene && object.getScene) {
  83995. this._scene = object.getScene();
  83996. }
  83997. if (!this._scene) {
  83998. return;
  83999. }
  84000. this._physicsEngine = this._scene.getPhysicsEngine();
  84001. if (!this._physicsEngine) {
  84002. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84003. }
  84004. else {
  84005. //set the object's quaternion, if not set
  84006. if (!this.object.rotationQuaternion) {
  84007. if (this.object.rotation) {
  84008. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84009. }
  84010. else {
  84011. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84012. }
  84013. }
  84014. //default options params
  84015. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84016. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84017. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84018. this._joints = [];
  84019. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84020. if (!this.object.parent || this._options.ignoreParent) {
  84021. this._init();
  84022. }
  84023. else if (this.object.parent.physicsImpostor) {
  84024. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84025. }
  84026. }
  84027. }
  84028. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84029. get: function () {
  84030. return this._isDisposed;
  84031. },
  84032. enumerable: true,
  84033. configurable: true
  84034. });
  84035. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84036. get: function () {
  84037. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84038. },
  84039. set: function (value) {
  84040. this.setMass(value);
  84041. },
  84042. enumerable: true,
  84043. configurable: true
  84044. });
  84045. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84046. get: function () {
  84047. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84048. },
  84049. set: function (value) {
  84050. if (!this._physicsEngine) {
  84051. return;
  84052. }
  84053. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84054. },
  84055. enumerable: true,
  84056. configurable: true
  84057. });
  84058. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84059. get: function () {
  84060. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84061. },
  84062. set: function (value) {
  84063. if (!this._physicsEngine) {
  84064. return;
  84065. }
  84066. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84067. },
  84068. enumerable: true,
  84069. configurable: true
  84070. });
  84071. /**
  84072. * This function will completly initialize this impostor.
  84073. * It will create a new body - but only if this mesh has no parent.
  84074. * If it has, this impostor will not be used other than to define the impostor
  84075. * of the child mesh.
  84076. */
  84077. PhysicsImpostor.prototype._init = function () {
  84078. if (!this._physicsEngine) {
  84079. return;
  84080. }
  84081. this._physicsEngine.removeImpostor(this);
  84082. this.physicsBody = null;
  84083. this._parent = this._parent || this._getPhysicsParent();
  84084. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84085. this._physicsEngine.addImpostor(this);
  84086. }
  84087. };
  84088. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84089. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84090. var parentMesh = this.object.parent;
  84091. return parentMesh.physicsImpostor;
  84092. }
  84093. return null;
  84094. };
  84095. /**
  84096. * Should a new body be generated.
  84097. */
  84098. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84099. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84100. };
  84101. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84102. this.forceUpdate();
  84103. };
  84104. /**
  84105. * Force a regeneration of this or the parent's impostor's body.
  84106. * Use under cautious - This will remove all joints already implemented.
  84107. */
  84108. PhysicsImpostor.prototype.forceUpdate = function () {
  84109. this._init();
  84110. if (this.parent && !this._options.ignoreParent) {
  84111. this.parent.forceUpdate();
  84112. }
  84113. };
  84114. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84115. /*public get mesh(): AbstractMesh {
  84116. return this._mesh;
  84117. }*/
  84118. /**
  84119. * Gets the body that holds this impostor. Either its own, or its parent.
  84120. */
  84121. get: function () {
  84122. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84123. },
  84124. /**
  84125. * Set the physics body. Used mainly by the physics engine/plugin
  84126. */
  84127. set: function (physicsBody) {
  84128. if (this._physicsBody && this._physicsEngine) {
  84129. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84130. }
  84131. this._physicsBody = physicsBody;
  84132. this.resetUpdateFlags();
  84133. },
  84134. enumerable: true,
  84135. configurable: true
  84136. });
  84137. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84138. get: function () {
  84139. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84140. },
  84141. set: function (value) {
  84142. this._parent = value;
  84143. },
  84144. enumerable: true,
  84145. configurable: true
  84146. });
  84147. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84148. this._bodyUpdateRequired = false;
  84149. };
  84150. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84151. if (this.object.getBoundingInfo) {
  84152. var q = this.object.rotationQuaternion;
  84153. //reset rotation
  84154. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84155. //calculate the world matrix with no rotation
  84156. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84157. var boundingInfo = this.object.getBoundingInfo();
  84158. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84159. //bring back the rotation
  84160. this.object.rotationQuaternion = q;
  84161. //calculate the world matrix with the new rotation
  84162. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84163. return size;
  84164. }
  84165. else {
  84166. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84167. }
  84168. };
  84169. PhysicsImpostor.prototype.getObjectCenter = function () {
  84170. if (this.object.getBoundingInfo) {
  84171. var boundingInfo = this.object.getBoundingInfo();
  84172. return boundingInfo.boundingBox.centerWorld;
  84173. }
  84174. else {
  84175. return this.object.position;
  84176. }
  84177. };
  84178. /**
  84179. * Get a specific parametes from the options parameter.
  84180. */
  84181. PhysicsImpostor.prototype.getParam = function (paramName) {
  84182. return this._options[paramName];
  84183. };
  84184. /**
  84185. * Sets a specific parameter in the options given to the physics plugin
  84186. */
  84187. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84188. this._options[paramName] = value;
  84189. this._bodyUpdateRequired = true;
  84190. };
  84191. /**
  84192. * Specifically change the body's mass option. Won't recreate the physics body object
  84193. */
  84194. PhysicsImpostor.prototype.setMass = function (mass) {
  84195. if (this.getParam("mass") !== mass) {
  84196. this.setParam("mass", mass);
  84197. }
  84198. if (this._physicsEngine) {
  84199. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84200. }
  84201. };
  84202. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84203. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84204. };
  84205. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84206. if (this._physicsEngine) {
  84207. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84208. }
  84209. };
  84210. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84211. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84212. };
  84213. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84214. if (this._physicsEngine) {
  84215. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84216. }
  84217. };
  84218. /**
  84219. * Execute a function with the physics plugin native code.
  84220. * Provide a function the will have two variables - the world object and the physics body object.
  84221. */
  84222. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84223. if (this._physicsEngine) {
  84224. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84225. }
  84226. };
  84227. /**
  84228. * Register a function that will be executed before the physics world is stepping forward.
  84229. */
  84230. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84231. this._onBeforePhysicsStepCallbacks.push(func);
  84232. };
  84233. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84234. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84235. if (index > -1) {
  84236. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84237. }
  84238. else {
  84239. BABYLON.Tools.Warn("Function to remove was not found");
  84240. }
  84241. };
  84242. /**
  84243. * Register a function that will be executed after the physics step
  84244. */
  84245. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84246. this._onAfterPhysicsStepCallbacks.push(func);
  84247. };
  84248. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84249. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84250. if (index > -1) {
  84251. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84252. }
  84253. else {
  84254. BABYLON.Tools.Warn("Function to remove was not found");
  84255. }
  84256. };
  84257. /**
  84258. * register a function that will be executed when this impostor collides against a different body.
  84259. */
  84260. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84261. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84262. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84263. };
  84264. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84265. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84266. var index = -1;
  84267. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84268. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84269. // chcek the arrays match
  84270. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84271. return collidedAgainstList.indexOf(impostor) > -1;
  84272. });
  84273. if (sameList) {
  84274. index = idx;
  84275. }
  84276. return sameList;
  84277. }
  84278. return false;
  84279. });
  84280. if (found) {
  84281. this._onPhysicsCollideCallbacks.splice(index, 1);
  84282. }
  84283. else {
  84284. BABYLON.Tools.Warn("Function to remove was not found");
  84285. }
  84286. };
  84287. PhysicsImpostor.prototype.getParentsRotation = function () {
  84288. var parent = this.object.parent;
  84289. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84290. while (parent) {
  84291. if (parent.rotationQuaternion) {
  84292. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84293. }
  84294. else {
  84295. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84296. }
  84297. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84298. parent = parent.parent;
  84299. }
  84300. return this._tmpQuat;
  84301. };
  84302. /**
  84303. * Apply a force
  84304. */
  84305. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84306. if (this._physicsEngine) {
  84307. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84308. }
  84309. return this;
  84310. };
  84311. /**
  84312. * Apply an impulse
  84313. */
  84314. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84315. if (this._physicsEngine) {
  84316. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84317. }
  84318. return this;
  84319. };
  84320. /**
  84321. * A help function to create a joint.
  84322. */
  84323. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84324. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84325. this.addJoint(otherImpostor, joint);
  84326. return this;
  84327. };
  84328. /**
  84329. * Add a joint to this impostor with a different impostor.
  84330. */
  84331. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84332. this._joints.push({
  84333. otherImpostor: otherImpostor,
  84334. joint: joint
  84335. });
  84336. if (this._physicsEngine) {
  84337. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84338. }
  84339. return this;
  84340. };
  84341. /**
  84342. * Will keep this body still, in a sleep mode.
  84343. */
  84344. PhysicsImpostor.prototype.sleep = function () {
  84345. if (this._physicsEngine) {
  84346. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84347. }
  84348. return this;
  84349. };
  84350. /**
  84351. * Wake the body up.
  84352. */
  84353. PhysicsImpostor.prototype.wakeUp = function () {
  84354. if (this._physicsEngine) {
  84355. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84356. }
  84357. return this;
  84358. };
  84359. PhysicsImpostor.prototype.clone = function (newObject) {
  84360. if (!newObject)
  84361. return null;
  84362. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84363. };
  84364. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84365. var _this = this;
  84366. //no dispose if no physics engine is available.
  84367. if (!this._physicsEngine) {
  84368. return;
  84369. }
  84370. this._joints.forEach(function (j) {
  84371. if (_this._physicsEngine) {
  84372. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84373. }
  84374. });
  84375. //dispose the physics body
  84376. this._physicsEngine.removeImpostor(this);
  84377. if (this.parent) {
  84378. this.parent.forceUpdate();
  84379. }
  84380. else {
  84381. /*this._object.getChildMeshes().forEach(function(mesh) {
  84382. if (mesh.physicsImpostor) {
  84383. if (disposeChildren) {
  84384. mesh.physicsImpostor.dispose();
  84385. mesh.physicsImpostor = null;
  84386. }
  84387. }
  84388. })*/
  84389. }
  84390. this._isDisposed = true;
  84391. };
  84392. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84393. this._deltaPosition.copyFrom(position);
  84394. };
  84395. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84396. if (!this._deltaRotation) {
  84397. this._deltaRotation = new BABYLON.Quaternion();
  84398. }
  84399. this._deltaRotation.copyFrom(rotation);
  84400. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84401. };
  84402. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84403. if (this._physicsEngine) {
  84404. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84405. }
  84406. return this;
  84407. };
  84408. PhysicsImpostor.prototype.getRadius = function () {
  84409. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84410. };
  84411. /**
  84412. * Sync a bone with this impostor
  84413. * @param bone The bone to sync to the impostor.
  84414. * @param boneMesh The mesh that the bone is influencing.
  84415. * @param jointPivot The pivot of the joint / bone in local space.
  84416. * @param distToJoint Optional distance from the impostor to the joint.
  84417. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84418. */
  84419. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84420. var tempVec = PhysicsImpostor._tmpVecs[0];
  84421. var mesh = this.object;
  84422. if (mesh.rotationQuaternion) {
  84423. if (adjustRotation) {
  84424. var tempQuat = PhysicsImpostor._tmpQuat;
  84425. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84426. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84427. }
  84428. else {
  84429. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84430. }
  84431. }
  84432. tempVec.x = 0;
  84433. tempVec.y = 0;
  84434. tempVec.z = 0;
  84435. if (jointPivot) {
  84436. tempVec.x = jointPivot.x;
  84437. tempVec.y = jointPivot.y;
  84438. tempVec.z = jointPivot.z;
  84439. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84440. if (distToJoint === undefined || distToJoint === null) {
  84441. distToJoint = jointPivot.length();
  84442. }
  84443. tempVec.x *= distToJoint;
  84444. tempVec.y *= distToJoint;
  84445. tempVec.z *= distToJoint;
  84446. }
  84447. if (bone.getParent()) {
  84448. tempVec.addInPlace(mesh.getAbsolutePosition());
  84449. bone.setAbsolutePosition(tempVec, boneMesh);
  84450. }
  84451. else {
  84452. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84453. boneMesh.position.x -= tempVec.x;
  84454. boneMesh.position.y -= tempVec.y;
  84455. boneMesh.position.z -= tempVec.z;
  84456. }
  84457. };
  84458. /**
  84459. * Sync impostor to a bone
  84460. * @param bone The bone that the impostor will be synced to.
  84461. * @param boneMesh The mesh that the bone is influencing.
  84462. * @param jointPivot The pivot of the joint / bone in local space.
  84463. * @param distToJoint Optional distance from the impostor to the joint.
  84464. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84465. * @param boneAxis Optional vector3 axis the bone is aligned with
  84466. */
  84467. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84468. var mesh = this.object;
  84469. if (mesh.rotationQuaternion) {
  84470. if (adjustRotation) {
  84471. var tempQuat = PhysicsImpostor._tmpQuat;
  84472. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84473. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84474. }
  84475. else {
  84476. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84477. }
  84478. }
  84479. var pos = PhysicsImpostor._tmpVecs[0];
  84480. var boneDir = PhysicsImpostor._tmpVecs[1];
  84481. if (!boneAxis) {
  84482. boneAxis = PhysicsImpostor._tmpVecs[2];
  84483. boneAxis.x = 0;
  84484. boneAxis.y = 1;
  84485. boneAxis.z = 0;
  84486. }
  84487. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84488. bone.getAbsolutePositionToRef(boneMesh, pos);
  84489. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84490. distToJoint = jointPivot.length();
  84491. }
  84492. if (distToJoint !== undefined && distToJoint !== null) {
  84493. pos.x += boneDir.x * distToJoint;
  84494. pos.y += boneDir.y * distToJoint;
  84495. pos.z += boneDir.z * distToJoint;
  84496. }
  84497. mesh.setAbsolutePosition(pos);
  84498. };
  84499. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84500. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84501. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84502. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84503. //Impostor types
  84504. PhysicsImpostor.NoImpostor = 0;
  84505. PhysicsImpostor.SphereImpostor = 1;
  84506. PhysicsImpostor.BoxImpostor = 2;
  84507. PhysicsImpostor.PlaneImpostor = 3;
  84508. PhysicsImpostor.MeshImpostor = 4;
  84509. PhysicsImpostor.CylinderImpostor = 7;
  84510. PhysicsImpostor.ParticleImpostor = 8;
  84511. PhysicsImpostor.HeightmapImpostor = 9;
  84512. return PhysicsImpostor;
  84513. }());
  84514. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84515. })(BABYLON || (BABYLON = {}));
  84516. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84517. var BABYLON;
  84518. (function (BABYLON) {
  84519. var PhysicsEngine = /** @class */ (function () {
  84520. function PhysicsEngine(gravity, _physicsPlugin) {
  84521. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84522. this._physicsPlugin = _physicsPlugin;
  84523. //new methods and parameters
  84524. this._impostors = [];
  84525. this._joints = [];
  84526. if (!this._physicsPlugin.isSupported()) {
  84527. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84528. + "Please make sure it is included.");
  84529. }
  84530. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84531. this.setGravity(gravity);
  84532. this.setTimeStep();
  84533. }
  84534. PhysicsEngine.prototype.setGravity = function (gravity) {
  84535. this.gravity = gravity;
  84536. this._physicsPlugin.setGravity(this.gravity);
  84537. };
  84538. /**
  84539. * Set the time step of the physics engine.
  84540. * default is 1/60.
  84541. * To slow it down, enter 1/600 for example.
  84542. * To speed it up, 1/30
  84543. * @param {number} newTimeStep the new timestep to apply to this world.
  84544. */
  84545. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84546. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84547. this._physicsPlugin.setTimeStep(newTimeStep);
  84548. };
  84549. /**
  84550. * Get the time step of the physics engine.
  84551. */
  84552. PhysicsEngine.prototype.getTimeStep = function () {
  84553. return this._physicsPlugin.getTimeStep();
  84554. };
  84555. PhysicsEngine.prototype.dispose = function () {
  84556. this._impostors.forEach(function (impostor) {
  84557. impostor.dispose();
  84558. });
  84559. this._physicsPlugin.dispose();
  84560. };
  84561. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84562. return this._physicsPlugin.name;
  84563. };
  84564. /**
  84565. * Adding a new impostor for the impostor tracking.
  84566. * This will be done by the impostor itself.
  84567. * @param {PhysicsImpostor} impostor the impostor to add
  84568. */
  84569. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84570. impostor.uniqueId = this._impostors.push(impostor);
  84571. //if no parent, generate the body
  84572. if (!impostor.parent) {
  84573. this._physicsPlugin.generatePhysicsBody(impostor);
  84574. }
  84575. };
  84576. /**
  84577. * Remove an impostor from the engine.
  84578. * This impostor and its mesh will not longer be updated by the physics engine.
  84579. * @param {PhysicsImpostor} impostor the impostor to remove
  84580. */
  84581. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84582. var index = this._impostors.indexOf(impostor);
  84583. if (index > -1) {
  84584. var removed = this._impostors.splice(index, 1);
  84585. //Is it needed?
  84586. if (removed.length) {
  84587. //this will also remove it from the world.
  84588. removed[0].physicsBody = null;
  84589. }
  84590. }
  84591. };
  84592. /**
  84593. * Add a joint to the physics engine
  84594. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84595. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84596. * @param {PhysicsJoint} the joint that will connect both impostors.
  84597. */
  84598. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84599. var impostorJoint = {
  84600. mainImpostor: mainImpostor,
  84601. connectedImpostor: connectedImpostor,
  84602. joint: joint
  84603. };
  84604. joint.physicsPlugin = this._physicsPlugin;
  84605. this._joints.push(impostorJoint);
  84606. this._physicsPlugin.generateJoint(impostorJoint);
  84607. };
  84608. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84609. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84610. return (impostorJoint.connectedImpostor === connectedImpostor
  84611. && impostorJoint.joint === joint
  84612. && impostorJoint.mainImpostor === mainImpostor);
  84613. });
  84614. if (matchingJoints.length) {
  84615. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84616. //TODO remove it from the list as well
  84617. }
  84618. };
  84619. /**
  84620. * Called by the scene. no need to call it.
  84621. */
  84622. PhysicsEngine.prototype._step = function (delta) {
  84623. var _this = this;
  84624. //check if any mesh has no body / requires an update
  84625. this._impostors.forEach(function (impostor) {
  84626. if (impostor.isBodyInitRequired()) {
  84627. _this._physicsPlugin.generatePhysicsBody(impostor);
  84628. }
  84629. });
  84630. if (delta > 0.1) {
  84631. delta = 0.1;
  84632. }
  84633. else if (delta <= 0) {
  84634. delta = 1.0 / 60.0;
  84635. }
  84636. this._physicsPlugin.executeStep(delta, this._impostors);
  84637. };
  84638. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84639. return this._physicsPlugin;
  84640. };
  84641. PhysicsEngine.prototype.getImpostors = function () {
  84642. return this._impostors;
  84643. };
  84644. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84645. for (var i = 0; i < this._impostors.length; ++i) {
  84646. if (this._impostors[i].object === object) {
  84647. return this._impostors[i];
  84648. }
  84649. }
  84650. return null;
  84651. };
  84652. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84653. for (var i = 0; i < this._impostors.length; ++i) {
  84654. if (this._impostors[i].physicsBody === body) {
  84655. return this._impostors[i];
  84656. }
  84657. }
  84658. return null;
  84659. };
  84660. // Statics
  84661. PhysicsEngine.Epsilon = 0.001;
  84662. return PhysicsEngine;
  84663. }());
  84664. BABYLON.PhysicsEngine = PhysicsEngine;
  84665. })(BABYLON || (BABYLON = {}));
  84666. //# sourceMappingURL=babylon.physicsEngine.js.map
  84667. var BABYLON;
  84668. (function (BABYLON) {
  84669. var PhysicsHelper = /** @class */ (function () {
  84670. function PhysicsHelper(scene) {
  84671. this._scene = scene;
  84672. this._physicsEngine = this._scene.getPhysicsEngine();
  84673. if (!this._physicsEngine) {
  84674. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84675. }
  84676. }
  84677. /**
  84678. * @param {Vector3} origin the origin of the explosion
  84679. * @param {number} radius the explosion radius
  84680. * @param {number} strength the explosion strength
  84681. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84682. */
  84683. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84684. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84685. if (!this._physicsEngine) {
  84686. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84687. return null;
  84688. }
  84689. var impostors = this._physicsEngine.getImpostors();
  84690. if (impostors.length === 0) {
  84691. return null;
  84692. }
  84693. var event = new PhysicsRadialExplosionEvent(this._scene);
  84694. impostors.forEach(function (impostor) {
  84695. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84696. if (!impostorForceAndContactPoint) {
  84697. return;
  84698. }
  84699. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84700. });
  84701. event.dispose(false);
  84702. return event;
  84703. };
  84704. /**
  84705. * @param {Vector3} origin the origin of the explosion
  84706. * @param {number} radius the explosion radius
  84707. * @param {number} strength the explosion strength
  84708. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84709. */
  84710. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84711. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84712. if (!this._physicsEngine) {
  84713. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84714. return null;
  84715. }
  84716. var impostors = this._physicsEngine.getImpostors();
  84717. if (impostors.length === 0) {
  84718. return null;
  84719. }
  84720. var event = new PhysicsRadialExplosionEvent(this._scene);
  84721. impostors.forEach(function (impostor) {
  84722. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84723. if (!impostorForceAndContactPoint) {
  84724. return;
  84725. }
  84726. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84727. });
  84728. event.dispose(false);
  84729. return event;
  84730. };
  84731. /**
  84732. * @param {Vector3} origin the origin of the explosion
  84733. * @param {number} radius the explosion radius
  84734. * @param {number} strength the explosion strength
  84735. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84736. */
  84737. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84738. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84739. if (!this._physicsEngine) {
  84740. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84741. return null;
  84742. }
  84743. var impostors = this._physicsEngine.getImpostors();
  84744. if (impostors.length === 0) {
  84745. return null;
  84746. }
  84747. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84748. event.dispose(false);
  84749. return event;
  84750. };
  84751. /**
  84752. * @param {Vector3} origin the origin of the updraft
  84753. * @param {number} radius the radius of the updraft
  84754. * @param {number} strength the strength of the updraft
  84755. * @param {number} height the height of the updraft
  84756. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84757. */
  84758. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84759. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84760. if (!this._physicsEngine) {
  84761. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84762. return null;
  84763. }
  84764. if (this._physicsEngine.getImpostors().length === 0) {
  84765. return null;
  84766. }
  84767. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84768. event.dispose(false);
  84769. return event;
  84770. };
  84771. /**
  84772. * @param {Vector3} origin the of the vortex
  84773. * @param {number} radius the radius of the vortex
  84774. * @param {number} strength the strength of the vortex
  84775. * @param {number} height the height of the vortex
  84776. */
  84777. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84778. if (!this._physicsEngine) {
  84779. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84780. return null;
  84781. }
  84782. if (this._physicsEngine.getImpostors().length === 0) {
  84783. return null;
  84784. }
  84785. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84786. event.dispose(false);
  84787. return event;
  84788. };
  84789. return PhysicsHelper;
  84790. }());
  84791. BABYLON.PhysicsHelper = PhysicsHelper;
  84792. /***** Radial explosion *****/
  84793. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84794. function PhysicsRadialExplosionEvent(scene) {
  84795. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84796. this._rays = [];
  84797. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84798. this._scene = scene;
  84799. }
  84800. /**
  84801. * Returns the data related to the radial explosion event (sphere & rays).
  84802. * @returns {PhysicsRadialExplosionEventData}
  84803. */
  84804. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84805. this._dataFetched = true;
  84806. return {
  84807. sphere: this._sphere,
  84808. rays: this._rays,
  84809. };
  84810. };
  84811. /**
  84812. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84813. * @param impostor
  84814. * @param {Vector3} origin the origin of the explosion
  84815. * @param {number} radius the explosion radius
  84816. * @param {number} strength the explosion strength
  84817. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84818. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84819. */
  84820. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84821. if (impostor.mass === 0) {
  84822. return null;
  84823. }
  84824. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84825. return null;
  84826. }
  84827. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84828. return null;
  84829. }
  84830. var impostorObjectCenter = impostor.getObjectCenter();
  84831. var direction = impostorObjectCenter.subtract(origin);
  84832. var ray = new BABYLON.Ray(origin, direction, radius);
  84833. this._rays.push(ray);
  84834. var hit = ray.intersectsMesh(impostor.object);
  84835. var contactPoint = hit.pickedPoint;
  84836. if (!contactPoint) {
  84837. return null;
  84838. }
  84839. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84840. if (distanceFromOrigin > radius) {
  84841. return null;
  84842. }
  84843. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84844. ? strength
  84845. : strength * (1 - (distanceFromOrigin / radius));
  84846. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84847. return { force: force, contactPoint: contactPoint };
  84848. };
  84849. /**
  84850. * Disposes the sphere.
  84851. * @param {bolean} force
  84852. */
  84853. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84854. var _this = this;
  84855. if (force === void 0) { force = true; }
  84856. if (force) {
  84857. this._sphere.dispose();
  84858. }
  84859. else {
  84860. setTimeout(function () {
  84861. if (!_this._dataFetched) {
  84862. _this._sphere.dispose();
  84863. }
  84864. }, 0);
  84865. }
  84866. };
  84867. /*** Helpers ***/
  84868. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84869. if (!this._sphere) {
  84870. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84871. this._sphere.isVisible = false;
  84872. }
  84873. };
  84874. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84875. var impostorObject = impostor.object;
  84876. this._prepareSphere();
  84877. this._sphere.position = origin;
  84878. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84879. this._sphere._updateBoundingInfo();
  84880. this._sphere.computeWorldMatrix(true);
  84881. return this._sphere.intersectsMesh(impostorObject, true);
  84882. };
  84883. return PhysicsRadialExplosionEvent;
  84884. }());
  84885. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84886. /***** Gravitational Field *****/
  84887. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84888. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84889. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84890. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84891. this._physicsHelper = physicsHelper;
  84892. this._scene = scene;
  84893. this._origin = origin;
  84894. this._radius = radius;
  84895. this._strength = strength;
  84896. this._falloff = falloff;
  84897. this._tickCallback = this._tick.bind(this);
  84898. }
  84899. /**
  84900. * Returns the data related to the gravitational field event (sphere).
  84901. * @returns {PhysicsGravitationalFieldEventData}
  84902. */
  84903. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84904. this._dataFetched = true;
  84905. return {
  84906. sphere: this._sphere,
  84907. };
  84908. };
  84909. /**
  84910. * Enables the gravitational field.
  84911. */
  84912. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84913. this._tickCallback.call(this);
  84914. this._scene.registerBeforeRender(this._tickCallback);
  84915. };
  84916. /**
  84917. * Disables the gravitational field.
  84918. */
  84919. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84920. this._scene.unregisterBeforeRender(this._tickCallback);
  84921. };
  84922. /**
  84923. * Disposes the sphere.
  84924. * @param {bolean} force
  84925. */
  84926. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84927. var _this = this;
  84928. if (force === void 0) { force = true; }
  84929. if (force) {
  84930. this._sphere.dispose();
  84931. }
  84932. else {
  84933. setTimeout(function () {
  84934. if (!_this._dataFetched) {
  84935. _this._sphere.dispose();
  84936. }
  84937. }, 0);
  84938. }
  84939. };
  84940. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84941. // Since the params won't change, we fetch the event only once
  84942. if (this._sphere) {
  84943. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84944. }
  84945. else {
  84946. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84947. if (radialExplosionEvent) {
  84948. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84949. }
  84950. }
  84951. };
  84952. return PhysicsGravitationalFieldEvent;
  84953. }());
  84954. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84955. /***** Updraft *****/
  84956. var PhysicsUpdraftEvent = /** @class */ (function () {
  84957. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84958. this._scene = _scene;
  84959. this._origin = _origin;
  84960. this._radius = _radius;
  84961. this._strength = _strength;
  84962. this._height = _height;
  84963. this._updraftMode = _updraftMode;
  84964. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84965. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84966. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84967. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84968. this._physicsEngine = this._scene.getPhysicsEngine();
  84969. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84970. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84971. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84972. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84973. }
  84974. this._tickCallback = this._tick.bind(this);
  84975. }
  84976. /**
  84977. * Returns the data related to the updraft event (cylinder).
  84978. * @returns {PhysicsUpdraftEventData}
  84979. */
  84980. PhysicsUpdraftEvent.prototype.getData = function () {
  84981. this._dataFetched = true;
  84982. return {
  84983. cylinder: this._cylinder,
  84984. };
  84985. };
  84986. /**
  84987. * Enables the updraft.
  84988. */
  84989. PhysicsUpdraftEvent.prototype.enable = function () {
  84990. this._tickCallback.call(this);
  84991. this._scene.registerBeforeRender(this._tickCallback);
  84992. };
  84993. /**
  84994. * Disables the cortex.
  84995. */
  84996. PhysicsUpdraftEvent.prototype.disable = function () {
  84997. this._scene.unregisterBeforeRender(this._tickCallback);
  84998. };
  84999. /**
  85000. * Disposes the sphere.
  85001. * @param {bolean} force
  85002. */
  85003. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85004. var _this = this;
  85005. if (force === void 0) { force = true; }
  85006. if (force) {
  85007. this._cylinder.dispose();
  85008. }
  85009. else {
  85010. setTimeout(function () {
  85011. if (!_this._dataFetched) {
  85012. _this._cylinder.dispose();
  85013. }
  85014. }, 0);
  85015. }
  85016. };
  85017. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85018. if (impostor.mass === 0) {
  85019. return null;
  85020. }
  85021. if (!this._intersectsWithCylinder(impostor)) {
  85022. return null;
  85023. }
  85024. var impostorObjectCenter = impostor.getObjectCenter();
  85025. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85026. var direction = this._originDirection;
  85027. }
  85028. else {
  85029. var direction = impostorObjectCenter.subtract(this._originTop);
  85030. }
  85031. var multiplier = this._strength * -1;
  85032. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85033. return { force: force, contactPoint: impostorObjectCenter };
  85034. };
  85035. PhysicsUpdraftEvent.prototype._tick = function () {
  85036. var _this = this;
  85037. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85038. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85039. if (!impostorForceAndContactPoint) {
  85040. return;
  85041. }
  85042. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85043. });
  85044. };
  85045. /*** Helpers ***/
  85046. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85047. if (!this._cylinder) {
  85048. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85049. height: this._height,
  85050. diameter: this._radius * 2,
  85051. }, this._scene);
  85052. this._cylinder.isVisible = false;
  85053. }
  85054. };
  85055. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85056. var impostorObject = impostor.object;
  85057. this._prepareCylinder();
  85058. this._cylinder.position = this._cylinderPosition;
  85059. return this._cylinder.intersectsMesh(impostorObject, true);
  85060. };
  85061. return PhysicsUpdraftEvent;
  85062. }());
  85063. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85064. /***** Vortex *****/
  85065. var PhysicsVortexEvent = /** @class */ (function () {
  85066. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85067. this._scene = _scene;
  85068. this._origin = _origin;
  85069. this._radius = _radius;
  85070. this._strength = _strength;
  85071. this._height = _height;
  85072. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85073. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85074. this._updraftMultiplier = 0.02;
  85075. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85076. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85077. this._physicsEngine = this._scene.getPhysicsEngine();
  85078. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85079. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85080. this._tickCallback = this._tick.bind(this);
  85081. }
  85082. /**
  85083. * Returns the data related to the vortex event (cylinder).
  85084. * @returns {PhysicsVortexEventData}
  85085. */
  85086. PhysicsVortexEvent.prototype.getData = function () {
  85087. this._dataFetched = true;
  85088. return {
  85089. cylinder: this._cylinder,
  85090. };
  85091. };
  85092. /**
  85093. * Enables the vortex.
  85094. */
  85095. PhysicsVortexEvent.prototype.enable = function () {
  85096. this._tickCallback.call(this);
  85097. this._scene.registerBeforeRender(this._tickCallback);
  85098. };
  85099. /**
  85100. * Disables the cortex.
  85101. */
  85102. PhysicsVortexEvent.prototype.disable = function () {
  85103. this._scene.unregisterBeforeRender(this._tickCallback);
  85104. };
  85105. /**
  85106. * Disposes the sphere.
  85107. * @param {bolean} force
  85108. */
  85109. PhysicsVortexEvent.prototype.dispose = function (force) {
  85110. var _this = this;
  85111. if (force === void 0) { force = true; }
  85112. if (force) {
  85113. this._cylinder.dispose();
  85114. }
  85115. else {
  85116. setTimeout(function () {
  85117. if (!_this._dataFetched) {
  85118. _this._cylinder.dispose();
  85119. }
  85120. }, 0);
  85121. }
  85122. };
  85123. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85124. if (impostor.mass === 0) {
  85125. return null;
  85126. }
  85127. if (!this._intersectsWithCylinder(impostor)) {
  85128. return null;
  85129. }
  85130. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85131. return null;
  85132. }
  85133. var impostorObjectCenter = impostor.getObjectCenter();
  85134. 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)
  85135. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85136. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85137. var hit = ray.intersectsMesh(impostor.object);
  85138. var contactPoint = hit.pickedPoint;
  85139. if (!contactPoint) {
  85140. return null;
  85141. }
  85142. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85143. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85144. var directionToOrigin = contactPoint.normalize();
  85145. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85146. directionToOrigin = directionToOrigin.negate();
  85147. }
  85148. // TODO: find a more physically based solution
  85149. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85150. var forceX = directionToOrigin.x * this._strength / 8;
  85151. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85152. var forceZ = directionToOrigin.z * this._strength / 8;
  85153. }
  85154. else {
  85155. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85156. var forceY = this._originTop.y * this._updraftMultiplier;
  85157. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85158. }
  85159. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85160. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85161. return { force: force, contactPoint: impostorObjectCenter };
  85162. };
  85163. PhysicsVortexEvent.prototype._tick = function () {
  85164. var _this = this;
  85165. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85166. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85167. if (!impostorForceAndContactPoint) {
  85168. return;
  85169. }
  85170. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85171. });
  85172. };
  85173. /*** Helpers ***/
  85174. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85175. if (!this._cylinder) {
  85176. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85177. height: this._height,
  85178. diameter: this._radius * 2,
  85179. }, this._scene);
  85180. this._cylinder.isVisible = false;
  85181. }
  85182. };
  85183. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85184. var impostorObject = impostor.object;
  85185. this._prepareCylinder();
  85186. this._cylinder.position = this._cylinderPosition;
  85187. return this._cylinder.intersectsMesh(impostorObject, true);
  85188. };
  85189. return PhysicsVortexEvent;
  85190. }());
  85191. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85192. /***** Enums *****/
  85193. /**
  85194. * The strenght of the force in correspondence to the distance of the affected object
  85195. */
  85196. var PhysicsRadialImpulseFalloff;
  85197. (function (PhysicsRadialImpulseFalloff) {
  85198. /** Defines that impulse is constant in strength across it's whole radius */
  85199. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85200. /** DEfines that impulse gets weaker if it's further from the origin */
  85201. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85202. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85203. /**
  85204. * The strenght of the force in correspondence to the distance of the affected object
  85205. */
  85206. var PhysicsUpdraftMode;
  85207. (function (PhysicsUpdraftMode) {
  85208. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85209. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85210. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85211. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85212. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85213. })(BABYLON || (BABYLON = {}));
  85214. //# sourceMappingURL=babylon.physicsHelper.js.map
  85215. var BABYLON;
  85216. (function (BABYLON) {
  85217. var CannonJSPlugin = /** @class */ (function () {
  85218. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85219. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85220. if (iterations === void 0) { iterations = 10; }
  85221. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85222. this.name = "CannonJSPlugin";
  85223. this._physicsMaterials = new Array();
  85224. this._fixedTimeStep = 1 / 60;
  85225. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85226. this.BJSCANNON = CANNON;
  85227. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85228. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85229. this._tmpPosition = BABYLON.Vector3.Zero();
  85230. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85231. this._tmpUnityRotation = new BABYLON.Quaternion();
  85232. if (!this.isSupported()) {
  85233. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85234. return;
  85235. }
  85236. this._extendNamespace();
  85237. this.world = new this.BJSCANNON.World();
  85238. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85239. this.world.solver.iterations = iterations;
  85240. }
  85241. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85242. this.world.gravity.copy(gravity);
  85243. };
  85244. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85245. this._fixedTimeStep = timeStep;
  85246. };
  85247. CannonJSPlugin.prototype.getTimeStep = function () {
  85248. return this._fixedTimeStep;
  85249. };
  85250. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85251. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85252. };
  85253. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85254. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85255. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85256. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85257. };
  85258. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85259. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85260. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85261. impostor.physicsBody.applyForce(impulse, worldPoint);
  85262. };
  85263. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85264. //parent-child relationship. Does this impostor has a parent impostor?
  85265. if (impostor.parent) {
  85266. if (impostor.physicsBody) {
  85267. this.removePhysicsBody(impostor);
  85268. //TODO is that needed?
  85269. impostor.forceUpdate();
  85270. }
  85271. return;
  85272. }
  85273. //should a new body be created for this impostor?
  85274. if (impostor.isBodyInitRequired()) {
  85275. var shape = this._createShape(impostor);
  85276. //unregister events, if body is being changed
  85277. var oldBody = impostor.physicsBody;
  85278. if (oldBody) {
  85279. this.removePhysicsBody(impostor);
  85280. }
  85281. //create the body and material
  85282. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85283. var bodyCreationObject = {
  85284. mass: impostor.getParam("mass"),
  85285. material: material
  85286. };
  85287. // A simple extend, in case native options were used.
  85288. var nativeOptions = impostor.getParam("nativeOptions");
  85289. for (var key in nativeOptions) {
  85290. if (nativeOptions.hasOwnProperty(key)) {
  85291. bodyCreationObject[key] = nativeOptions[key];
  85292. }
  85293. }
  85294. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85295. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85296. this.world.addEventListener("preStep", impostor.beforeStep);
  85297. this.world.addEventListener("postStep", impostor.afterStep);
  85298. impostor.physicsBody.addShape(shape);
  85299. this.world.add(impostor.physicsBody);
  85300. //try to keep the body moving in the right direction by taking old properties.
  85301. //Should be tested!
  85302. if (oldBody) {
  85303. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85304. impostor.physicsBody[param].copy(oldBody[param]);
  85305. });
  85306. }
  85307. this._processChildMeshes(impostor);
  85308. }
  85309. //now update the body's transformation
  85310. this._updatePhysicsBodyTransformation(impostor);
  85311. };
  85312. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85313. var _this = this;
  85314. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85315. var currentRotation = mainImpostor.object.rotationQuaternion;
  85316. if (meshChildren.length) {
  85317. var processMesh = function (localPosition, mesh) {
  85318. if (!currentRotation || !mesh.rotationQuaternion) {
  85319. return;
  85320. }
  85321. var childImpostor = mesh.getPhysicsImpostor();
  85322. if (childImpostor) {
  85323. var parent = childImpostor.parent;
  85324. if (parent !== mainImpostor) {
  85325. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85326. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85327. if (childImpostor.physicsBody) {
  85328. _this.removePhysicsBody(childImpostor);
  85329. childImpostor.physicsBody = null;
  85330. }
  85331. childImpostor.parent = mainImpostor;
  85332. childImpostor.resetUpdateFlags();
  85333. 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));
  85334. //Add the mass of the children.
  85335. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85336. }
  85337. }
  85338. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85339. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85340. };
  85341. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85342. }
  85343. };
  85344. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85345. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85346. this.world.removeEventListener("preStep", impostor.beforeStep);
  85347. this.world.removeEventListener("postStep", impostor.afterStep);
  85348. this.world.remove(impostor.physicsBody);
  85349. };
  85350. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85351. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85352. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85353. if (!mainBody || !connectedBody) {
  85354. return;
  85355. }
  85356. var constraint;
  85357. var jointData = impostorJoint.joint.jointData;
  85358. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85359. var constraintData = {
  85360. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85361. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85362. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85363. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85364. maxForce: jointData.nativeParams.maxForce,
  85365. collideConnected: !!jointData.collision
  85366. };
  85367. switch (impostorJoint.joint.type) {
  85368. case BABYLON.PhysicsJoint.HingeJoint:
  85369. case BABYLON.PhysicsJoint.Hinge2Joint:
  85370. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85371. break;
  85372. case BABYLON.PhysicsJoint.DistanceJoint:
  85373. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85374. break;
  85375. case BABYLON.PhysicsJoint.SpringJoint:
  85376. var springData = jointData;
  85377. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85378. restLength: springData.length,
  85379. stiffness: springData.stiffness,
  85380. damping: springData.damping,
  85381. localAnchorA: constraintData.pivotA,
  85382. localAnchorB: constraintData.pivotB
  85383. });
  85384. break;
  85385. case BABYLON.PhysicsJoint.LockJoint:
  85386. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85387. break;
  85388. case BABYLON.PhysicsJoint.PointToPointJoint:
  85389. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85390. default:
  85391. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85392. break;
  85393. }
  85394. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85395. constraint.collideConnected = !!jointData.collision;
  85396. impostorJoint.joint.physicsJoint = constraint;
  85397. //don't add spring as constraint, as it is not one.
  85398. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85399. this.world.addConstraint(constraint);
  85400. }
  85401. else {
  85402. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85403. constraint.applyForce();
  85404. });
  85405. }
  85406. };
  85407. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85408. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85409. };
  85410. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85411. var index;
  85412. var mat;
  85413. for (index = 0; index < this._physicsMaterials.length; index++) {
  85414. mat = this._physicsMaterials[index];
  85415. if (mat.friction === friction && mat.restitution === restitution) {
  85416. return mat;
  85417. }
  85418. }
  85419. var currentMat = new this.BJSCANNON.Material(name);
  85420. currentMat.friction = friction;
  85421. currentMat.restitution = restitution;
  85422. this._physicsMaterials.push(currentMat);
  85423. return currentMat;
  85424. };
  85425. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85426. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85427. };
  85428. CannonJSPlugin.prototype._createShape = function (impostor) {
  85429. var object = impostor.object;
  85430. var returnValue;
  85431. var extendSize = impostor.getObjectExtendSize();
  85432. switch (impostor.type) {
  85433. case BABYLON.PhysicsImpostor.SphereImpostor:
  85434. var radiusX = extendSize.x;
  85435. var radiusY = extendSize.y;
  85436. var radiusZ = extendSize.z;
  85437. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85438. break;
  85439. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85440. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85441. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85442. break;
  85443. case BABYLON.PhysicsImpostor.BoxImpostor:
  85444. var box = extendSize.scale(0.5);
  85445. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85446. break;
  85447. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85448. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85449. returnValue = new this.BJSCANNON.Plane();
  85450. break;
  85451. case BABYLON.PhysicsImpostor.MeshImpostor:
  85452. // should transform the vertex data to world coordinates!!
  85453. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85454. var rawFaces = object.getIndices ? object.getIndices() : [];
  85455. if (!rawVerts)
  85456. return;
  85457. // get only scale! so the object could transform correctly.
  85458. var oldPosition = object.position.clone();
  85459. var oldRotation = object.rotation && object.rotation.clone();
  85460. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85461. object.position.copyFromFloats(0, 0, 0);
  85462. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85463. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85464. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85465. var transform = object.computeWorldMatrix(true);
  85466. // convert rawVerts to object space
  85467. var temp = new Array();
  85468. var index;
  85469. for (index = 0; index < rawVerts.length; index += 3) {
  85470. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85471. }
  85472. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85473. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85474. //now set back the transformation!
  85475. object.position.copyFrom(oldPosition);
  85476. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85477. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85478. break;
  85479. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85480. var oldPosition2 = object.position.clone();
  85481. var oldRotation2 = object.rotation && object.rotation.clone();
  85482. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85483. object.position.copyFromFloats(0, 0, 0);
  85484. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85485. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85486. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85487. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85488. returnValue = this._createHeightmap(object);
  85489. object.position.copyFrom(oldPosition2);
  85490. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85491. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85492. object.computeWorldMatrix(true);
  85493. break;
  85494. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85495. returnValue = new this.BJSCANNON.Particle();
  85496. break;
  85497. }
  85498. return returnValue;
  85499. };
  85500. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85501. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85502. var transform = object.computeWorldMatrix(true);
  85503. // convert rawVerts to object space
  85504. var temp = new Array();
  85505. var index;
  85506. for (index = 0; index < pos.length; index += 3) {
  85507. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85508. }
  85509. pos = temp;
  85510. var matrix = new Array();
  85511. //For now pointDepth will not be used and will be automatically calculated.
  85512. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85513. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85514. var boundingInfo = object.getBoundingInfo();
  85515. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85516. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85517. var elementSize = dim * 2 / arraySize;
  85518. for (var i = 0; i < pos.length; i = i + 3) {
  85519. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85520. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85521. var y = -pos[i + 2] + minY;
  85522. if (!matrix[x]) {
  85523. matrix[x] = [];
  85524. }
  85525. if (!matrix[x][z]) {
  85526. matrix[x][z] = y;
  85527. }
  85528. matrix[x][z] = Math.max(y, matrix[x][z]);
  85529. }
  85530. for (var x = 0; x <= arraySize; ++x) {
  85531. if (!matrix[x]) {
  85532. var loc = 1;
  85533. while (!matrix[(x + loc) % arraySize]) {
  85534. loc++;
  85535. }
  85536. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85537. //console.log("missing x", x);
  85538. }
  85539. for (var z = 0; z <= arraySize; ++z) {
  85540. if (!matrix[x][z]) {
  85541. var loc = 1;
  85542. var newValue;
  85543. while (newValue === undefined) {
  85544. newValue = matrix[x][(z + loc++) % arraySize];
  85545. }
  85546. matrix[x][z] = newValue;
  85547. }
  85548. }
  85549. }
  85550. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85551. elementSize: elementSize
  85552. });
  85553. //For future reference, needed for body transformation
  85554. shape.minY = minY;
  85555. return shape;
  85556. };
  85557. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85558. var object = impostor.object;
  85559. //make sure it is updated...
  85560. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85561. // The delta between the mesh position and the mesh bounding box center
  85562. var bInfo = object.getBoundingInfo();
  85563. if (!bInfo)
  85564. return;
  85565. var center = impostor.getObjectCenter();
  85566. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85567. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85568. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85569. this._tmpPosition.copyFrom(center);
  85570. var quaternion = object.rotationQuaternion;
  85571. if (!quaternion) {
  85572. return;
  85573. }
  85574. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85575. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85576. //-90 DEG in X, precalculated
  85577. quaternion = quaternion.multiply(this._minus90X);
  85578. //Invert! (Precalculated, 90 deg in X)
  85579. //No need to clone. this will never change.
  85580. impostor.setDeltaRotation(this._plus90X);
  85581. }
  85582. //If it is a heightfield, if should be centered.
  85583. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85584. var mesh = object;
  85585. var boundingInfo = mesh.getBoundingInfo();
  85586. //calculate the correct body position:
  85587. var rotationQuaternion = mesh.rotationQuaternion;
  85588. mesh.rotationQuaternion = this._tmpUnityRotation;
  85589. mesh.computeWorldMatrix(true);
  85590. //get original center with no rotation
  85591. var c = center.clone();
  85592. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85593. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85594. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85595. mesh.setPreTransformMatrix(p);
  85596. mesh.computeWorldMatrix(true);
  85597. //calculate the translation
  85598. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85599. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85600. //add it inverted to the delta
  85601. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85602. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85603. //rotation is back
  85604. mesh.rotationQuaternion = rotationQuaternion;
  85605. mesh.setPreTransformMatrix(oldPivot);
  85606. mesh.computeWorldMatrix(true);
  85607. }
  85608. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85609. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85610. //this._tmpPosition.copyFrom(object.position);
  85611. }
  85612. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85613. //Now update the impostor object
  85614. impostor.physicsBody.position.copy(this._tmpPosition);
  85615. impostor.physicsBody.quaternion.copy(quaternion);
  85616. };
  85617. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85618. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85619. if (impostor.object.rotationQuaternion) {
  85620. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85621. }
  85622. };
  85623. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85624. impostor.physicsBody.position.copy(newPosition);
  85625. impostor.physicsBody.quaternion.copy(newRotation);
  85626. };
  85627. CannonJSPlugin.prototype.isSupported = function () {
  85628. return this.BJSCANNON !== undefined;
  85629. };
  85630. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85631. impostor.physicsBody.velocity.copy(velocity);
  85632. };
  85633. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85634. impostor.physicsBody.angularVelocity.copy(velocity);
  85635. };
  85636. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85637. var v = impostor.physicsBody.velocity;
  85638. if (!v) {
  85639. return null;
  85640. }
  85641. return new BABYLON.Vector3(v.x, v.y, v.z);
  85642. };
  85643. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85644. var v = impostor.physicsBody.angularVelocity;
  85645. if (!v) {
  85646. return null;
  85647. }
  85648. return new BABYLON.Vector3(v.x, v.y, v.z);
  85649. };
  85650. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85651. impostor.physicsBody.mass = mass;
  85652. impostor.physicsBody.updateMassProperties();
  85653. };
  85654. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85655. return impostor.physicsBody.mass;
  85656. };
  85657. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85658. return impostor.physicsBody.material.friction;
  85659. };
  85660. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85661. impostor.physicsBody.material.friction = friction;
  85662. };
  85663. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85664. return impostor.physicsBody.material.restitution;
  85665. };
  85666. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85667. impostor.physicsBody.material.restitution = restitution;
  85668. };
  85669. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85670. impostor.physicsBody.sleep();
  85671. };
  85672. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85673. impostor.physicsBody.wakeUp();
  85674. };
  85675. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85676. joint.physicsJoint.distance = maxDistance;
  85677. };
  85678. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85679. // if (!motorIndex) {
  85680. // joint.physicsJoint.enableMotor();
  85681. // }
  85682. // }
  85683. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85684. // if (!motorIndex) {
  85685. // joint.physicsJoint.disableMotor();
  85686. // }
  85687. // }
  85688. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85689. if (!motorIndex) {
  85690. joint.physicsJoint.enableMotor();
  85691. joint.physicsJoint.setMotorSpeed(speed);
  85692. if (maxForce) {
  85693. this.setLimit(joint, maxForce);
  85694. }
  85695. }
  85696. };
  85697. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85698. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85699. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85700. };
  85701. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85702. var body = impostor.physicsBody;
  85703. mesh.position.x = body.position.x;
  85704. mesh.position.y = body.position.y;
  85705. mesh.position.z = body.position.z;
  85706. if (mesh.rotationQuaternion) {
  85707. mesh.rotationQuaternion.x = body.quaternion.x;
  85708. mesh.rotationQuaternion.y = body.quaternion.y;
  85709. mesh.rotationQuaternion.z = body.quaternion.z;
  85710. mesh.rotationQuaternion.w = body.quaternion.w;
  85711. }
  85712. };
  85713. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85714. var shape = impostor.physicsBody.shapes[0];
  85715. return shape.boundingSphereRadius;
  85716. };
  85717. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85718. var shape = impostor.physicsBody.shapes[0];
  85719. result.x = shape.halfExtents.x * 2;
  85720. result.y = shape.halfExtents.y * 2;
  85721. result.z = shape.halfExtents.z * 2;
  85722. };
  85723. CannonJSPlugin.prototype.dispose = function () {
  85724. };
  85725. CannonJSPlugin.prototype._extendNamespace = function () {
  85726. //this will force cannon to execute at least one step when using interpolation
  85727. var step_tmp1 = new this.BJSCANNON.Vec3();
  85728. var Engine = this.BJSCANNON;
  85729. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85730. maxSubSteps = maxSubSteps || 10;
  85731. timeSinceLastCalled = timeSinceLastCalled || 0;
  85732. if (timeSinceLastCalled === 0) {
  85733. this.internalStep(dt);
  85734. this.time += dt;
  85735. }
  85736. else {
  85737. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85738. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85739. var t0 = performance.now();
  85740. for (var i = 0; i !== internalSteps; i++) {
  85741. this.internalStep(dt);
  85742. if (performance.now() - t0 > dt * 1000) {
  85743. break;
  85744. }
  85745. }
  85746. this.time += timeSinceLastCalled;
  85747. var h = this.time % dt;
  85748. var h_div_dt = h / dt;
  85749. var interpvelo = step_tmp1;
  85750. var bodies = this.bodies;
  85751. for (var j = 0; j !== bodies.length; j++) {
  85752. var b = bodies[j];
  85753. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85754. b.position.vsub(b.previousPosition, interpvelo);
  85755. interpvelo.scale(h_div_dt, interpvelo);
  85756. b.position.vadd(interpvelo, b.interpolatedPosition);
  85757. }
  85758. else {
  85759. b.interpolatedPosition.copy(b.position);
  85760. b.interpolatedQuaternion.copy(b.quaternion);
  85761. }
  85762. }
  85763. }
  85764. };
  85765. };
  85766. return CannonJSPlugin;
  85767. }());
  85768. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85769. })(BABYLON || (BABYLON = {}));
  85770. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85771. var BABYLON;
  85772. (function (BABYLON) {
  85773. var OimoJSPlugin = /** @class */ (function () {
  85774. function OimoJSPlugin(iterations) {
  85775. this.name = "OimoJSPlugin";
  85776. this._tmpImpostorsArray = [];
  85777. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85778. this.BJSOIMO = OIMO;
  85779. this.world = new this.BJSOIMO.World({
  85780. iterations: iterations
  85781. });
  85782. this.world.clear();
  85783. }
  85784. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85785. this.world.gravity.copy(gravity);
  85786. };
  85787. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85788. this.world.timeStep = timeStep;
  85789. };
  85790. OimoJSPlugin.prototype.getTimeStep = function () {
  85791. return this.world.timeStep;
  85792. };
  85793. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85794. var _this = this;
  85795. impostors.forEach(function (impostor) {
  85796. impostor.beforeStep();
  85797. });
  85798. this.world.step();
  85799. impostors.forEach(function (impostor) {
  85800. impostor.afterStep();
  85801. //update the ordered impostors array
  85802. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85803. });
  85804. //check for collisions
  85805. var contact = this.world.contacts;
  85806. while (contact !== null) {
  85807. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85808. contact = contact.next;
  85809. continue;
  85810. }
  85811. //is this body colliding with any other? get the impostor
  85812. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85813. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85814. if (!mainImpostor || !collidingImpostor) {
  85815. contact = contact.next;
  85816. continue;
  85817. }
  85818. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85819. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85820. contact = contact.next;
  85821. }
  85822. };
  85823. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85824. var mass = impostor.physicsBody.mass;
  85825. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85826. };
  85827. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85828. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85829. this.applyImpulse(impostor, force, contactPoint);
  85830. };
  85831. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85832. var _this = this;
  85833. //parent-child relationship. Does this impostor has a parent impostor?
  85834. if (impostor.parent) {
  85835. if (impostor.physicsBody) {
  85836. this.removePhysicsBody(impostor);
  85837. //TODO is that needed?
  85838. impostor.forceUpdate();
  85839. }
  85840. return;
  85841. }
  85842. if (impostor.isBodyInitRequired()) {
  85843. var bodyConfig = {
  85844. name: impostor.uniqueId,
  85845. //Oimo must have mass, also for static objects.
  85846. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85847. size: [],
  85848. type: [],
  85849. pos: [],
  85850. posShape: [],
  85851. rot: [],
  85852. rotShape: [],
  85853. move: impostor.getParam("mass") !== 0,
  85854. density: impostor.getParam("mass"),
  85855. friction: impostor.getParam("friction"),
  85856. restitution: impostor.getParam("restitution"),
  85857. //Supporting older versions of Oimo
  85858. world: this.world
  85859. };
  85860. var impostors = [impostor];
  85861. var addToArray = function (parent) {
  85862. if (!parent.getChildMeshes)
  85863. return;
  85864. parent.getChildMeshes().forEach(function (m) {
  85865. if (m.physicsImpostor) {
  85866. impostors.push(m.physicsImpostor);
  85867. //m.physicsImpostor._init();
  85868. }
  85869. });
  85870. };
  85871. addToArray(impostor.object);
  85872. var checkWithEpsilon_1 = function (value) {
  85873. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85874. };
  85875. impostors.forEach(function (i) {
  85876. if (!i.object.rotationQuaternion) {
  85877. return;
  85878. }
  85879. //get the correct bounding box
  85880. var oldQuaternion = i.object.rotationQuaternion;
  85881. var rot = oldQuaternion.toEulerAngles();
  85882. var extendSize = i.getObjectExtendSize();
  85883. var radToDeg = 57.295779513082320876;
  85884. if (i === impostor) {
  85885. var center = impostor.getObjectCenter();
  85886. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85887. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85888. //Can also use Array.prototype.push.apply
  85889. bodyConfig.pos.push(center.x);
  85890. bodyConfig.pos.push(center.y);
  85891. bodyConfig.pos.push(center.z);
  85892. bodyConfig.posShape.push(0, 0, 0);
  85893. //tmp solution
  85894. bodyConfig.rot.push(rot.x * radToDeg);
  85895. bodyConfig.rot.push(rot.y * radToDeg);
  85896. bodyConfig.rot.push(rot.z * radToDeg);
  85897. bodyConfig.rotShape.push(0, 0, 0);
  85898. }
  85899. else {
  85900. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85901. bodyConfig.posShape.push(localPosition.x);
  85902. bodyConfig.posShape.push(localPosition.y);
  85903. bodyConfig.posShape.push(localPosition.z);
  85904. bodyConfig.pos.push(0, 0, 0);
  85905. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85906. bodyConfig.rot.push(0);
  85907. bodyConfig.rot.push(0);
  85908. bodyConfig.rot.push(0);
  85909. bodyConfig.rotShape.push(rot.x * radToDeg);
  85910. bodyConfig.rotShape.push(rot.y * radToDeg);
  85911. bodyConfig.rotShape.push(rot.z * radToDeg);
  85912. }
  85913. // register mesh
  85914. switch (i.type) {
  85915. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85916. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85917. case BABYLON.PhysicsImpostor.SphereImpostor:
  85918. var radiusX = extendSize.x;
  85919. var radiusY = extendSize.y;
  85920. var radiusZ = extendSize.z;
  85921. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85922. bodyConfig.type.push('sphere');
  85923. //due to the way oimo works with compounds, add 3 times
  85924. bodyConfig.size.push(size);
  85925. bodyConfig.size.push(size);
  85926. bodyConfig.size.push(size);
  85927. break;
  85928. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85929. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85930. var sizeY = checkWithEpsilon_1(extendSize.y);
  85931. bodyConfig.type.push('cylinder');
  85932. bodyConfig.size.push(sizeX);
  85933. bodyConfig.size.push(sizeY);
  85934. //due to the way oimo works with compounds, add one more value.
  85935. bodyConfig.size.push(sizeY);
  85936. break;
  85937. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85938. case BABYLON.PhysicsImpostor.BoxImpostor:
  85939. default:
  85940. var sizeX = checkWithEpsilon_1(extendSize.x);
  85941. var sizeY = checkWithEpsilon_1(extendSize.y);
  85942. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85943. bodyConfig.type.push('box');
  85944. //if (i === impostor) {
  85945. bodyConfig.size.push(sizeX);
  85946. bodyConfig.size.push(sizeY);
  85947. bodyConfig.size.push(sizeZ);
  85948. //} else {
  85949. // bodyConfig.size.push(0,0,0);
  85950. //}
  85951. break;
  85952. }
  85953. //actually not needed, but hey...
  85954. i.object.rotationQuaternion = oldQuaternion;
  85955. });
  85956. impostor.physicsBody = this.world.add(bodyConfig);
  85957. }
  85958. else {
  85959. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85960. }
  85961. impostor.setDeltaPosition(this._tmpPositionVector);
  85962. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85963. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85964. };
  85965. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85966. //impostor.physicsBody.dispose();
  85967. //Same as : (older oimo versions)
  85968. this.world.removeRigidBody(impostor.physicsBody);
  85969. };
  85970. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85971. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85972. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85973. if (!mainBody || !connectedBody) {
  85974. return;
  85975. }
  85976. var jointData = impostorJoint.joint.jointData;
  85977. var options = jointData.nativeParams || {};
  85978. var type;
  85979. var nativeJointData = {
  85980. body1: mainBody,
  85981. body2: connectedBody,
  85982. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85983. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85984. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85985. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85986. min: options.min,
  85987. max: options.max,
  85988. collision: options.collision || jointData.collision,
  85989. spring: options.spring,
  85990. //supporting older version of Oimo
  85991. world: this.world
  85992. };
  85993. switch (impostorJoint.joint.type) {
  85994. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85995. type = "jointBall";
  85996. break;
  85997. case BABYLON.PhysicsJoint.SpringJoint:
  85998. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85999. var springData = jointData;
  86000. nativeJointData.min = springData.length || nativeJointData.min;
  86001. //Max should also be set, just make sure it is at least min
  86002. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86003. case BABYLON.PhysicsJoint.DistanceJoint:
  86004. type = "jointDistance";
  86005. nativeJointData.max = jointData.maxDistance;
  86006. break;
  86007. case BABYLON.PhysicsJoint.PrismaticJoint:
  86008. type = "jointPrisme";
  86009. break;
  86010. case BABYLON.PhysicsJoint.SliderJoint:
  86011. type = "jointSlide";
  86012. break;
  86013. case BABYLON.PhysicsJoint.WheelJoint:
  86014. type = "jointWheel";
  86015. break;
  86016. case BABYLON.PhysicsJoint.HingeJoint:
  86017. default:
  86018. type = "jointHinge";
  86019. break;
  86020. }
  86021. nativeJointData.type = type;
  86022. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86023. };
  86024. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86025. //Bug in Oimo prevents us from disposing a joint in the playground
  86026. //joint.joint.physicsJoint.dispose();
  86027. //So we will bruteforce it!
  86028. try {
  86029. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86030. }
  86031. catch (e) {
  86032. BABYLON.Tools.Warn(e);
  86033. }
  86034. };
  86035. OimoJSPlugin.prototype.isSupported = function () {
  86036. return this.BJSOIMO !== undefined;
  86037. };
  86038. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86039. if (!impostor.physicsBody.sleeping) {
  86040. //TODO check that
  86041. /*if (impostor.physicsBody.shapes.next) {
  86042. var parentShape = this._getLastShape(impostor.physicsBody);
  86043. impostor.object.position.copyFrom(parentShape.position);
  86044. console.log(parentShape.position);
  86045. } else {*/
  86046. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86047. //}
  86048. if (impostor.object.rotationQuaternion) {
  86049. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86050. }
  86051. }
  86052. };
  86053. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86054. var body = impostor.physicsBody;
  86055. body.position.copy(newPosition);
  86056. body.orientation.copy(newRotation);
  86057. body.syncShapes();
  86058. body.awake();
  86059. };
  86060. /*private _getLastShape(body: any): any {
  86061. var lastShape = body.shapes;
  86062. while (lastShape.next) {
  86063. lastShape = lastShape.next;
  86064. }
  86065. return lastShape;
  86066. }*/
  86067. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86068. impostor.physicsBody.linearVelocity.copy(velocity);
  86069. };
  86070. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86071. impostor.physicsBody.angularVelocity.copy(velocity);
  86072. };
  86073. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86074. var v = impostor.physicsBody.linearVelocity;
  86075. if (!v) {
  86076. return null;
  86077. }
  86078. return new BABYLON.Vector3(v.x, v.y, v.z);
  86079. };
  86080. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86081. var v = impostor.physicsBody.angularVelocity;
  86082. if (!v) {
  86083. return null;
  86084. }
  86085. return new BABYLON.Vector3(v.x, v.y, v.z);
  86086. };
  86087. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86088. var staticBody = mass === 0;
  86089. //this will actually set the body's density and not its mass.
  86090. //But this is how oimo treats the mass variable.
  86091. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86092. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86093. };
  86094. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86095. return impostor.physicsBody.shapes.density;
  86096. };
  86097. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86098. return impostor.physicsBody.shapes.friction;
  86099. };
  86100. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86101. impostor.physicsBody.shapes.friction = friction;
  86102. };
  86103. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86104. return impostor.physicsBody.shapes.restitution;
  86105. };
  86106. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86107. impostor.physicsBody.shapes.restitution = restitution;
  86108. };
  86109. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86110. impostor.physicsBody.sleep();
  86111. };
  86112. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86113. impostor.physicsBody.awake();
  86114. };
  86115. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86116. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86117. if (minDistance !== void 0) {
  86118. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86119. }
  86120. };
  86121. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86122. //TODO separate rotational and transational motors.
  86123. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86124. if (motor) {
  86125. motor.setMotor(speed, maxForce);
  86126. }
  86127. };
  86128. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86129. //TODO separate rotational and transational motors.
  86130. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86131. if (motor) {
  86132. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86133. }
  86134. };
  86135. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86136. var body = impostor.physicsBody;
  86137. mesh.position.x = body.position.x;
  86138. mesh.position.y = body.position.y;
  86139. mesh.position.z = body.position.z;
  86140. if (mesh.rotationQuaternion) {
  86141. mesh.rotationQuaternion.x = body.orientation.x;
  86142. mesh.rotationQuaternion.y = body.orientation.y;
  86143. mesh.rotationQuaternion.z = body.orientation.z;
  86144. mesh.rotationQuaternion.w = body.orientation.s;
  86145. }
  86146. };
  86147. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86148. return impostor.physicsBody.shapes.radius;
  86149. };
  86150. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86151. var shape = impostor.physicsBody.shapes;
  86152. result.x = shape.halfWidth * 2;
  86153. result.y = shape.halfHeight * 2;
  86154. result.z = shape.halfDepth * 2;
  86155. };
  86156. OimoJSPlugin.prototype.dispose = function () {
  86157. this.world.clear();
  86158. };
  86159. return OimoJSPlugin;
  86160. }());
  86161. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86162. })(BABYLON || (BABYLON = {}));
  86163. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86164. var BABYLON;
  86165. (function (BABYLON) {
  86166. /*
  86167. * Based on jsTGALoader - Javascript loader for TGA file
  86168. * By Vincent Thibault
  86169. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86170. */
  86171. var TGATools = /** @class */ (function () {
  86172. function TGATools() {
  86173. }
  86174. TGATools.GetTGAHeader = function (data) {
  86175. var offset = 0;
  86176. var header = {
  86177. id_length: data[offset++],
  86178. colormap_type: data[offset++],
  86179. image_type: data[offset++],
  86180. colormap_index: data[offset++] | data[offset++] << 8,
  86181. colormap_length: data[offset++] | data[offset++] << 8,
  86182. colormap_size: data[offset++],
  86183. origin: [
  86184. data[offset++] | data[offset++] << 8,
  86185. data[offset++] | data[offset++] << 8
  86186. ],
  86187. width: data[offset++] | data[offset++] << 8,
  86188. height: data[offset++] | data[offset++] << 8,
  86189. pixel_size: data[offset++],
  86190. flags: data[offset++]
  86191. };
  86192. return header;
  86193. };
  86194. TGATools.UploadContent = function (gl, data) {
  86195. // Not enough data to contain header ?
  86196. if (data.length < 19) {
  86197. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86198. return;
  86199. }
  86200. // Read Header
  86201. var offset = 18;
  86202. var header = TGATools.GetTGAHeader(data);
  86203. // Assume it's a valid Targa file.
  86204. if (header.id_length + offset > data.length) {
  86205. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86206. return;
  86207. }
  86208. // Skip not needed data
  86209. offset += header.id_length;
  86210. var use_rle = false;
  86211. var use_pal = false;
  86212. var use_grey = false;
  86213. // Get some informations.
  86214. switch (header.image_type) {
  86215. case TGATools._TYPE_RLE_INDEXED:
  86216. use_rle = true;
  86217. case TGATools._TYPE_INDEXED:
  86218. use_pal = true;
  86219. break;
  86220. case TGATools._TYPE_RLE_RGB:
  86221. use_rle = true;
  86222. case TGATools._TYPE_RGB:
  86223. // use_rgb = true;
  86224. break;
  86225. case TGATools._TYPE_RLE_GREY:
  86226. use_rle = true;
  86227. case TGATools._TYPE_GREY:
  86228. use_grey = true;
  86229. break;
  86230. }
  86231. var pixel_data;
  86232. // var numAlphaBits = header.flags & 0xf;
  86233. var pixel_size = header.pixel_size >> 3;
  86234. var pixel_total = header.width * header.height * pixel_size;
  86235. // Read palettes
  86236. var palettes;
  86237. if (use_pal) {
  86238. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86239. }
  86240. // Read LRE
  86241. if (use_rle) {
  86242. pixel_data = new Uint8Array(pixel_total);
  86243. var c, count, i;
  86244. var localOffset = 0;
  86245. var pixels = new Uint8Array(pixel_size);
  86246. while (offset < pixel_total && localOffset < pixel_total) {
  86247. c = data[offset++];
  86248. count = (c & 0x7f) + 1;
  86249. // RLE pixels
  86250. if (c & 0x80) {
  86251. // Bind pixel tmp array
  86252. for (i = 0; i < pixel_size; ++i) {
  86253. pixels[i] = data[offset++];
  86254. }
  86255. // Copy pixel array
  86256. for (i = 0; i < count; ++i) {
  86257. pixel_data.set(pixels, localOffset + i * pixel_size);
  86258. }
  86259. localOffset += pixel_size * count;
  86260. }
  86261. // Raw pixels
  86262. else {
  86263. count *= pixel_size;
  86264. for (i = 0; i < count; ++i) {
  86265. pixel_data[localOffset + i] = data[offset++];
  86266. }
  86267. localOffset += count;
  86268. }
  86269. }
  86270. }
  86271. // RAW Pixels
  86272. else {
  86273. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86274. }
  86275. // Load to texture
  86276. var x_start, y_start, x_step, y_step, y_end, x_end;
  86277. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86278. default:
  86279. case TGATools._ORIGIN_UL:
  86280. x_start = 0;
  86281. x_step = 1;
  86282. x_end = header.width;
  86283. y_start = 0;
  86284. y_step = 1;
  86285. y_end = header.height;
  86286. break;
  86287. case TGATools._ORIGIN_BL:
  86288. x_start = 0;
  86289. x_step = 1;
  86290. x_end = header.width;
  86291. y_start = header.height - 1;
  86292. y_step = -1;
  86293. y_end = -1;
  86294. break;
  86295. case TGATools._ORIGIN_UR:
  86296. x_start = header.width - 1;
  86297. x_step = -1;
  86298. x_end = -1;
  86299. y_start = 0;
  86300. y_step = 1;
  86301. y_end = header.height;
  86302. break;
  86303. case TGATools._ORIGIN_BR:
  86304. x_start = header.width - 1;
  86305. x_step = -1;
  86306. x_end = -1;
  86307. y_start = header.height - 1;
  86308. y_step = -1;
  86309. y_end = -1;
  86310. break;
  86311. }
  86312. // Load the specify method
  86313. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86314. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86315. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86316. };
  86317. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86318. var image = pixel_data, colormap = palettes;
  86319. var width = header.width, height = header.height;
  86320. var color, i = 0, x, y;
  86321. var imageData = new Uint8Array(width * height * 4);
  86322. for (y = y_start; y !== y_end; y += y_step) {
  86323. for (x = x_start; x !== x_end; x += x_step, i++) {
  86324. color = image[i];
  86325. imageData[(x + width * y) * 4 + 3] = 255;
  86326. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86327. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86328. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86329. }
  86330. }
  86331. return imageData;
  86332. };
  86333. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86334. var image = pixel_data;
  86335. var width = header.width, height = header.height;
  86336. var color, i = 0, x, y;
  86337. var imageData = new Uint8Array(width * height * 4);
  86338. for (y = y_start; y !== y_end; y += y_step) {
  86339. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86340. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86341. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86342. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86343. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86344. imageData[(x + width * y) * 4 + 0] = r;
  86345. imageData[(x + width * y) * 4 + 1] = g;
  86346. imageData[(x + width * y) * 4 + 2] = b;
  86347. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86348. }
  86349. }
  86350. return imageData;
  86351. };
  86352. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86353. var image = pixel_data;
  86354. var width = header.width, height = header.height;
  86355. var i = 0, x, y;
  86356. var imageData = new Uint8Array(width * height * 4);
  86357. for (y = y_start; y !== y_end; y += y_step) {
  86358. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86359. imageData[(x + width * y) * 4 + 3] = 255;
  86360. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86361. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86362. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86363. }
  86364. }
  86365. return imageData;
  86366. };
  86367. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86368. var image = pixel_data;
  86369. var width = header.width, height = header.height;
  86370. var i = 0, x, y;
  86371. var imageData = new Uint8Array(width * height * 4);
  86372. for (y = y_start; y !== y_end; y += y_step) {
  86373. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86374. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86375. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86376. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86377. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86378. }
  86379. }
  86380. return imageData;
  86381. };
  86382. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86383. var image = pixel_data;
  86384. var width = header.width, height = header.height;
  86385. var color, i = 0, x, y;
  86386. var imageData = new Uint8Array(width * height * 4);
  86387. for (y = y_start; y !== y_end; y += y_step) {
  86388. for (x = x_start; x !== x_end; x += x_step, i++) {
  86389. color = image[i];
  86390. imageData[(x + width * y) * 4 + 0] = color;
  86391. imageData[(x + width * y) * 4 + 1] = color;
  86392. imageData[(x + width * y) * 4 + 2] = color;
  86393. imageData[(x + width * y) * 4 + 3] = 255;
  86394. }
  86395. }
  86396. return imageData;
  86397. };
  86398. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86399. var image = pixel_data;
  86400. var width = header.width, height = header.height;
  86401. var i = 0, x, y;
  86402. var imageData = new Uint8Array(width * height * 4);
  86403. for (y = y_start; y !== y_end; y += y_step) {
  86404. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86405. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86406. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86407. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86408. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86409. }
  86410. }
  86411. return imageData;
  86412. };
  86413. //private static _TYPE_NO_DATA = 0;
  86414. TGATools._TYPE_INDEXED = 1;
  86415. TGATools._TYPE_RGB = 2;
  86416. TGATools._TYPE_GREY = 3;
  86417. TGATools._TYPE_RLE_INDEXED = 9;
  86418. TGATools._TYPE_RLE_RGB = 10;
  86419. TGATools._TYPE_RLE_GREY = 11;
  86420. TGATools._ORIGIN_MASK = 0x30;
  86421. TGATools._ORIGIN_SHIFT = 0x04;
  86422. TGATools._ORIGIN_BL = 0x00;
  86423. TGATools._ORIGIN_BR = 0x01;
  86424. TGATools._ORIGIN_UL = 0x02;
  86425. TGATools._ORIGIN_UR = 0x03;
  86426. return TGATools;
  86427. }());
  86428. BABYLON.TGATools = TGATools;
  86429. })(BABYLON || (BABYLON = {}));
  86430. //# sourceMappingURL=babylon.tga.js.map
  86431. var BABYLON;
  86432. (function (BABYLON) {
  86433. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86434. // All values and structures referenced from:
  86435. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86436. var DDS_MAGIC = 0x20534444;
  86437. var
  86438. //DDSD_CAPS = 0x1,
  86439. //DDSD_HEIGHT = 0x2,
  86440. //DDSD_WIDTH = 0x4,
  86441. //DDSD_PITCH = 0x8,
  86442. //DDSD_PIXELFORMAT = 0x1000,
  86443. DDSD_MIPMAPCOUNT = 0x20000;
  86444. //DDSD_LINEARSIZE = 0x80000,
  86445. //DDSD_DEPTH = 0x800000;
  86446. // var DDSCAPS_COMPLEX = 0x8,
  86447. // DDSCAPS_MIPMAP = 0x400000,
  86448. // DDSCAPS_TEXTURE = 0x1000;
  86449. var DDSCAPS2_CUBEMAP = 0x200;
  86450. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86451. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86452. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86453. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86454. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86455. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86456. // DDSCAPS2_VOLUME = 0x200000;
  86457. var
  86458. //DDPF_ALPHAPIXELS = 0x1,
  86459. //DDPF_ALPHA = 0x2,
  86460. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86461. //DDPF_YUV = 0x200,
  86462. DDPF_LUMINANCE = 0x20000;
  86463. function FourCCToInt32(value) {
  86464. return value.charCodeAt(0) +
  86465. (value.charCodeAt(1) << 8) +
  86466. (value.charCodeAt(2) << 16) +
  86467. (value.charCodeAt(3) << 24);
  86468. }
  86469. function Int32ToFourCC(value) {
  86470. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86471. }
  86472. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86473. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86474. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86475. var FOURCC_DX10 = FourCCToInt32("DX10");
  86476. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86477. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86478. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86479. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86480. var headerLengthInt = 31; // The header length in 32 bit ints
  86481. // Offsets into the header array
  86482. var off_magic = 0;
  86483. var off_size = 1;
  86484. var off_flags = 2;
  86485. var off_height = 3;
  86486. var off_width = 4;
  86487. var off_mipmapCount = 7;
  86488. var off_pfFlags = 20;
  86489. var off_pfFourCC = 21;
  86490. var off_RGBbpp = 22;
  86491. var off_RMask = 23;
  86492. var off_GMask = 24;
  86493. var off_BMask = 25;
  86494. var off_AMask = 26;
  86495. // var off_caps1 = 27;
  86496. var off_caps2 = 28;
  86497. // var off_caps3 = 29;
  86498. // var off_caps4 = 30;
  86499. var off_dxgiFormat = 32;
  86500. ;
  86501. var DDSTools = /** @class */ (function () {
  86502. function DDSTools() {
  86503. }
  86504. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86505. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86506. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86507. var mipmapCount = 1;
  86508. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86509. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86510. }
  86511. var fourCC = header[off_pfFourCC];
  86512. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86513. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86514. switch (fourCC) {
  86515. case FOURCC_D3DFMT_R16G16B16A16F:
  86516. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86517. break;
  86518. case FOURCC_D3DFMT_R32G32B32A32F:
  86519. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86520. break;
  86521. case FOURCC_DX10:
  86522. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86523. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86524. break;
  86525. }
  86526. }
  86527. return {
  86528. width: header[off_width],
  86529. height: header[off_height],
  86530. mipmapCount: mipmapCount,
  86531. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86532. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86533. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86534. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86535. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86536. dxgiFormat: dxgiFormat,
  86537. textureType: textureType
  86538. };
  86539. };
  86540. DDSTools._ToHalfFloat = function (value) {
  86541. if (!DDSTools._FloatView) {
  86542. DDSTools._FloatView = new Float32Array(1);
  86543. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86544. }
  86545. DDSTools._FloatView[0] = value;
  86546. var x = DDSTools._Int32View[0];
  86547. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86548. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86549. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86550. /* If zero, or denormal, or exponent underflows too much for a denormal
  86551. * half, return signed zero. */
  86552. if (e < 103) {
  86553. return bits;
  86554. }
  86555. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86556. if (e > 142) {
  86557. bits |= 0x7c00;
  86558. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86559. * not Inf, so make sure we set one mantissa bit too. */
  86560. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86561. return bits;
  86562. }
  86563. /* If exponent underflows but not too much, return a denormal */
  86564. if (e < 113) {
  86565. m |= 0x0800;
  86566. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86567. * to 1, which is OK. */
  86568. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86569. return bits;
  86570. }
  86571. bits |= ((e - 112) << 10) | (m >> 1);
  86572. bits += m & 1;
  86573. return bits;
  86574. };
  86575. DDSTools._FromHalfFloat = function (value) {
  86576. var s = (value & 0x8000) >> 15;
  86577. var e = (value & 0x7C00) >> 10;
  86578. var f = value & 0x03FF;
  86579. if (e === 0) {
  86580. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86581. }
  86582. else if (e == 0x1F) {
  86583. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86584. }
  86585. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86586. };
  86587. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86588. var destArray = new Float32Array(dataLength);
  86589. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86590. var index = 0;
  86591. for (var y = 0; y < height; y++) {
  86592. for (var x = 0; x < width; x++) {
  86593. var srcPos = (x + y * width) * 4;
  86594. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86595. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86596. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86597. if (DDSTools.StoreLODInAlphaChannel) {
  86598. destArray[index + 3] = lod;
  86599. }
  86600. else {
  86601. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86602. }
  86603. index += 4;
  86604. }
  86605. }
  86606. return destArray;
  86607. };
  86608. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86609. if (DDSTools.StoreLODInAlphaChannel) {
  86610. var destArray = new Uint16Array(dataLength);
  86611. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86612. var index = 0;
  86613. for (var y = 0; y < height; y++) {
  86614. for (var x = 0; x < width; x++) {
  86615. var srcPos = (x + y * width) * 4;
  86616. destArray[index] = srcData[srcPos];
  86617. destArray[index + 1] = srcData[srcPos + 1];
  86618. destArray[index + 2] = srcData[srcPos + 2];
  86619. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86620. index += 4;
  86621. }
  86622. }
  86623. return destArray;
  86624. }
  86625. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86626. };
  86627. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86628. if (DDSTools.StoreLODInAlphaChannel) {
  86629. var destArray = new Float32Array(dataLength);
  86630. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86631. var index = 0;
  86632. for (var y = 0; y < height; y++) {
  86633. for (var x = 0; x < width; x++) {
  86634. var srcPos = (x + y * width) * 4;
  86635. destArray[index] = srcData[srcPos];
  86636. destArray[index + 1] = srcData[srcPos + 1];
  86637. destArray[index + 2] = srcData[srcPos + 2];
  86638. destArray[index + 3] = lod;
  86639. index += 4;
  86640. }
  86641. }
  86642. return destArray;
  86643. }
  86644. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86645. };
  86646. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86647. var destArray = new Uint8Array(dataLength);
  86648. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86649. var index = 0;
  86650. for (var y = 0; y < height; y++) {
  86651. for (var x = 0; x < width; x++) {
  86652. var srcPos = (x + y * width) * 4;
  86653. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86654. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86655. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86656. if (DDSTools.StoreLODInAlphaChannel) {
  86657. destArray[index + 3] = lod;
  86658. }
  86659. else {
  86660. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86661. }
  86662. index += 4;
  86663. }
  86664. }
  86665. return destArray;
  86666. };
  86667. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86668. var destArray = new Uint8Array(dataLength);
  86669. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86670. var index = 0;
  86671. for (var y = 0; y < height; y++) {
  86672. for (var x = 0; x < width; x++) {
  86673. var srcPos = (x + y * width) * 4;
  86674. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86675. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86676. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86677. if (DDSTools.StoreLODInAlphaChannel) {
  86678. destArray[index + 3] = lod;
  86679. }
  86680. else {
  86681. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86682. }
  86683. index += 4;
  86684. }
  86685. }
  86686. return destArray;
  86687. };
  86688. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86689. var byteArray = new Uint8Array(dataLength);
  86690. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86691. var index = 0;
  86692. for (var y = 0; y < height; y++) {
  86693. for (var x = 0; x < width; x++) {
  86694. var srcPos = (x + y * width) * 4;
  86695. byteArray[index] = srcData[srcPos + rOffset];
  86696. byteArray[index + 1] = srcData[srcPos + gOffset];
  86697. byteArray[index + 2] = srcData[srcPos + bOffset];
  86698. byteArray[index + 3] = srcData[srcPos + aOffset];
  86699. index += 4;
  86700. }
  86701. }
  86702. return byteArray;
  86703. };
  86704. DDSTools._ExtractLongWordOrder = function (value) {
  86705. if (value === 0 || value === 255 || value === -16777216) {
  86706. return 0;
  86707. }
  86708. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86709. };
  86710. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86711. var byteArray = new Uint8Array(dataLength);
  86712. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86713. var index = 0;
  86714. for (var y = 0; y < height; y++) {
  86715. for (var x = 0; x < width; x++) {
  86716. var srcPos = (x + y * width) * 3;
  86717. byteArray[index] = srcData[srcPos + rOffset];
  86718. byteArray[index + 1] = srcData[srcPos + gOffset];
  86719. byteArray[index + 2] = srcData[srcPos + bOffset];
  86720. index += 3;
  86721. }
  86722. }
  86723. return byteArray;
  86724. };
  86725. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86726. var byteArray = new Uint8Array(dataLength);
  86727. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86728. var index = 0;
  86729. for (var y = 0; y < height; y++) {
  86730. for (var x = 0; x < width; x++) {
  86731. var srcPos = (x + y * width);
  86732. byteArray[index] = srcData[srcPos];
  86733. index++;
  86734. }
  86735. }
  86736. return byteArray;
  86737. };
  86738. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86739. if (lodIndex === void 0) { lodIndex = -1; }
  86740. var sphericalPolynomialFaces = null;
  86741. if (info.sphericalPolynomial) {
  86742. sphericalPolynomialFaces = new Array();
  86743. }
  86744. var ext = engine.getCaps().s3tc;
  86745. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86746. var fourCC, width, height, dataLength = 0, dataOffset;
  86747. var byteArray, mipmapCount, mip;
  86748. var internalFormat = 0;
  86749. var format = 0;
  86750. var blockBytes = 1;
  86751. if (header[off_magic] !== DDS_MAGIC) {
  86752. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86753. return;
  86754. }
  86755. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86756. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86757. return;
  86758. }
  86759. if (info.isCompressed && !ext) {
  86760. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86761. return;
  86762. }
  86763. var bpp = header[off_RGBbpp];
  86764. dataOffset = header[off_size] + 4;
  86765. var computeFormats = false;
  86766. if (info.isFourCC) {
  86767. fourCC = header[off_pfFourCC];
  86768. switch (fourCC) {
  86769. case FOURCC_DXT1:
  86770. blockBytes = 8;
  86771. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86772. break;
  86773. case FOURCC_DXT3:
  86774. blockBytes = 16;
  86775. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86776. break;
  86777. case FOURCC_DXT5:
  86778. blockBytes = 16;
  86779. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86780. break;
  86781. case FOURCC_D3DFMT_R16G16B16A16F:
  86782. computeFormats = true;
  86783. break;
  86784. case FOURCC_D3DFMT_R32G32B32A32F:
  86785. computeFormats = true;
  86786. break;
  86787. case FOURCC_DX10:
  86788. // There is an additionnal header so dataOffset need to be changed
  86789. dataOffset += 5 * 4; // 5 uints
  86790. var supported = false;
  86791. switch (info.dxgiFormat) {
  86792. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86793. computeFormats = true;
  86794. supported = true;
  86795. break;
  86796. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86797. info.isRGB = true;
  86798. info.isFourCC = false;
  86799. bpp = 32;
  86800. supported = true;
  86801. break;
  86802. }
  86803. if (supported) {
  86804. break;
  86805. }
  86806. default:
  86807. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86808. return;
  86809. }
  86810. }
  86811. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86812. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86813. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86814. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86815. if (computeFormats) {
  86816. format = engine._getWebGLTextureType(info.textureType);
  86817. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86818. }
  86819. mipmapCount = 1;
  86820. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86821. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86822. }
  86823. for (var face = 0; face < faces; face++) {
  86824. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86825. width = header[off_width];
  86826. height = header[off_height];
  86827. for (mip = 0; mip < mipmapCount; ++mip) {
  86828. if (lodIndex === -1 || lodIndex === mip) {
  86829. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86830. var i = (lodIndex === -1) ? mip : 0;
  86831. if (!info.isCompressed && info.isFourCC) {
  86832. dataLength = width * height * 4;
  86833. var floatArray = null;
  86834. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86835. if (bpp === 128) {
  86836. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86837. if (sphericalPolynomialFaces && i == 0) {
  86838. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86839. }
  86840. }
  86841. else if (bpp === 64) {
  86842. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86843. if (sphericalPolynomialFaces && i == 0) {
  86844. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86845. }
  86846. }
  86847. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86848. format = engine._getWebGLTextureType(info.textureType);
  86849. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86850. }
  86851. else {
  86852. if (bpp === 128) {
  86853. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86854. if (sphericalPolynomialFaces && i == 0) {
  86855. sphericalPolynomialFaces.push(floatArray);
  86856. }
  86857. }
  86858. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86859. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86860. if (sphericalPolynomialFaces && i == 0) {
  86861. sphericalPolynomialFaces.push(floatArray);
  86862. }
  86863. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86864. format = engine._getWebGLTextureType(info.textureType);
  86865. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86866. }
  86867. else { // 64
  86868. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86869. if (sphericalPolynomialFaces && i == 0) {
  86870. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86871. }
  86872. }
  86873. }
  86874. if (floatArray) {
  86875. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86876. }
  86877. }
  86878. else if (info.isRGB) {
  86879. if (bpp === 24) {
  86880. dataLength = width * height * 3;
  86881. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86882. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86883. }
  86884. else { // 32
  86885. dataLength = width * height * 4;
  86886. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86887. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86888. }
  86889. }
  86890. else if (info.isLuminance) {
  86891. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86892. var unpaddedRowSize = width;
  86893. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86894. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86895. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86896. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86897. }
  86898. else {
  86899. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86900. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86901. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86902. }
  86903. }
  86904. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86905. width *= 0.5;
  86906. height *= 0.5;
  86907. width = Math.max(1.0, width);
  86908. height = Math.max(1.0, height);
  86909. }
  86910. if (currentFace !== undefined) {
  86911. // Loading a single face
  86912. break;
  86913. }
  86914. }
  86915. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86916. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86917. size: header[off_width],
  86918. right: sphericalPolynomialFaces[0],
  86919. left: sphericalPolynomialFaces[1],
  86920. up: sphericalPolynomialFaces[2],
  86921. down: sphericalPolynomialFaces[3],
  86922. front: sphericalPolynomialFaces[4],
  86923. back: sphericalPolynomialFaces[5],
  86924. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86925. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86926. gammaSpace: false,
  86927. });
  86928. }
  86929. else {
  86930. info.sphericalPolynomial = undefined;
  86931. }
  86932. };
  86933. DDSTools.StoreLODInAlphaChannel = false;
  86934. return DDSTools;
  86935. }());
  86936. BABYLON.DDSTools = DDSTools;
  86937. })(BABYLON || (BABYLON = {}));
  86938. //# sourceMappingURL=babylon.dds.js.map
  86939. var BABYLON;
  86940. (function (BABYLON) {
  86941. /**
  86942. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86943. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86944. */
  86945. var KhronosTextureContainer = /** @class */ (function () {
  86946. /**
  86947. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86948. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86949. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86950. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86951. */
  86952. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86953. this.arrayBuffer = arrayBuffer;
  86954. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86955. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86956. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86957. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86958. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86959. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86960. BABYLON.Tools.Error("texture missing KTX identifier");
  86961. return;
  86962. }
  86963. // load the reset of the header in native 32 bit int
  86964. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86965. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86966. var oppositeEndianess = header[0] === 0x01020304;
  86967. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86968. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86969. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86970. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86971. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86972. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86973. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86974. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86975. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86976. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86977. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86978. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86979. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86980. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86981. if (this.glType !== 0) {
  86982. BABYLON.Tools.Error("only compressed formats currently supported");
  86983. return;
  86984. }
  86985. else {
  86986. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86987. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86988. }
  86989. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86990. BABYLON.Tools.Error("only 2D textures currently supported");
  86991. return;
  86992. }
  86993. if (this.numberOfArrayElements !== 0) {
  86994. BABYLON.Tools.Error("texture arrays not currently supported");
  86995. return;
  86996. }
  86997. if (this.numberOfFaces !== facesExpected) {
  86998. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86999. return;
  87000. }
  87001. // we now have a completely validated file, so could use existence of loadType as success
  87002. // would need to make this more elaborate & adjust checks above to support more than one load type
  87003. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87004. }
  87005. // not as fast hardware based, but will probably never need to use
  87006. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87007. return ((val & 0xFF) << 24)
  87008. | ((val & 0xFF00) << 8)
  87009. | ((val >> 8) & 0xFF00)
  87010. | ((val >> 24) & 0xFF);
  87011. };
  87012. /**
  87013. * It is assumed that the texture has already been created & is currently bound
  87014. */
  87015. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87016. switch (this.loadType) {
  87017. case KhronosTextureContainer.COMPRESSED_2D:
  87018. this._upload2DCompressedLevels(gl, loadMipmaps);
  87019. break;
  87020. case KhronosTextureContainer.TEX_2D:
  87021. case KhronosTextureContainer.COMPRESSED_3D:
  87022. case KhronosTextureContainer.TEX_3D:
  87023. }
  87024. };
  87025. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87026. // initialize width & height for level 1
  87027. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87028. var width = this.pixelWidth;
  87029. var height = this.pixelHeight;
  87030. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87031. for (var level = 0; level < mipmapCount; level++) {
  87032. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87033. for (var face = 0; face < this.numberOfFaces; face++) {
  87034. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87035. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  87036. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87037. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  87038. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87039. }
  87040. width = Math.max(1.0, width * 0.5);
  87041. height = Math.max(1.0, height * 0.5);
  87042. }
  87043. };
  87044. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87045. // load types
  87046. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87047. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87048. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87049. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87050. return KhronosTextureContainer;
  87051. }());
  87052. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87053. })(BABYLON || (BABYLON = {}));
  87054. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87055. var BABYLON;
  87056. (function (BABYLON) {
  87057. var Debug;
  87058. (function (Debug) {
  87059. /**
  87060. * Class used to render a debug view of a given skeleton
  87061. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87062. */
  87063. var SkeletonViewer = /** @class */ (function () {
  87064. /**
  87065. * Creates a new SkeletonViewer
  87066. * @param skeleton defines the skeleton to render
  87067. * @param mesh defines the mesh attached to the skeleton
  87068. * @param scene defines the hosting scene
  87069. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87070. * @param renderingGroupId defines the rendering group id to use with the viewer
  87071. */
  87072. function SkeletonViewer(
  87073. /** defines the skeleton to render */
  87074. skeleton,
  87075. /** defines the mesh attached to the skeleton */
  87076. mesh, scene,
  87077. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87078. autoUpdateBonesMatrices,
  87079. /** defines the rendering group id to use with the viewer */
  87080. renderingGroupId) {
  87081. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87082. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87083. this.skeleton = skeleton;
  87084. this.mesh = mesh;
  87085. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87086. this.renderingGroupId = renderingGroupId;
  87087. /** Gets or sets the color used to render the skeleton */
  87088. this.color = BABYLON.Color3.White();
  87089. this._debugLines = new Array();
  87090. this._isEnabled = false;
  87091. this._scene = scene;
  87092. this.update();
  87093. this._renderFunction = this.update.bind(this);
  87094. }
  87095. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87096. get: function () {
  87097. return this._isEnabled;
  87098. },
  87099. /** Gets or sets a boolean indicating if the viewer is enabled */
  87100. set: function (value) {
  87101. if (this._isEnabled === value) {
  87102. return;
  87103. }
  87104. this._isEnabled = value;
  87105. if (value) {
  87106. this._scene.registerBeforeRender(this._renderFunction);
  87107. }
  87108. else {
  87109. this._scene.unregisterBeforeRender(this._renderFunction);
  87110. }
  87111. },
  87112. enumerable: true,
  87113. configurable: true
  87114. });
  87115. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87116. if (x === void 0) { x = 0; }
  87117. if (y === void 0) { y = 0; }
  87118. if (z === void 0) { z = 0; }
  87119. var tmat = BABYLON.Tmp.Matrix[0];
  87120. var parentBone = bone.getParent();
  87121. tmat.copyFrom(bone.getLocalMatrix());
  87122. if (x !== 0 || y !== 0 || z !== 0) {
  87123. var tmat2 = BABYLON.Tmp.Matrix[1];
  87124. BABYLON.Matrix.IdentityToRef(tmat2);
  87125. tmat2.m[12] = x;
  87126. tmat2.m[13] = y;
  87127. tmat2.m[14] = z;
  87128. tmat2.multiplyToRef(tmat, tmat);
  87129. }
  87130. if (parentBone) {
  87131. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87132. }
  87133. tmat.multiplyToRef(meshMat, tmat);
  87134. position.x = tmat.m[12];
  87135. position.y = tmat.m[13];
  87136. position.z = tmat.m[14];
  87137. };
  87138. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87139. var len = bones.length;
  87140. var meshPos = this.mesh.position;
  87141. for (var i = 0; i < len; i++) {
  87142. var bone = bones[i];
  87143. var points = this._debugLines[i];
  87144. if (!points) {
  87145. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87146. this._debugLines[i] = points;
  87147. }
  87148. this._getBonePosition(points[0], bone, meshMat);
  87149. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87150. points[0].subtractInPlace(meshPos);
  87151. points[1].subtractInPlace(meshPos);
  87152. }
  87153. };
  87154. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87155. var len = bones.length;
  87156. var boneNum = 0;
  87157. var meshPos = this.mesh.position;
  87158. for (var i = len - 1; i >= 0; i--) {
  87159. var childBone = bones[i];
  87160. var parentBone = childBone.getParent();
  87161. if (!parentBone) {
  87162. continue;
  87163. }
  87164. var points = this._debugLines[boneNum];
  87165. if (!points) {
  87166. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87167. this._debugLines[boneNum] = points;
  87168. }
  87169. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87170. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87171. points[0].subtractInPlace(meshPos);
  87172. points[1].subtractInPlace(meshPos);
  87173. boneNum++;
  87174. }
  87175. };
  87176. /** Update the viewer to sync with current skeleton state */
  87177. SkeletonViewer.prototype.update = function () {
  87178. if (this.autoUpdateBonesMatrices) {
  87179. this.skeleton.computeAbsoluteTransforms();
  87180. }
  87181. if (this.skeleton.bones[0].length === undefined) {
  87182. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87183. }
  87184. else {
  87185. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87186. }
  87187. if (!this._debugMesh) {
  87188. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87189. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87190. }
  87191. else {
  87192. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87193. }
  87194. this._debugMesh.position.copyFrom(this.mesh.position);
  87195. this._debugMesh.color = this.color;
  87196. };
  87197. /** Release associated resources */
  87198. SkeletonViewer.prototype.dispose = function () {
  87199. if (this._debugMesh) {
  87200. this.isEnabled = false;
  87201. this._debugMesh.dispose();
  87202. this._debugMesh = null;
  87203. }
  87204. };
  87205. return SkeletonViewer;
  87206. }());
  87207. Debug.SkeletonViewer = SkeletonViewer;
  87208. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87209. })(BABYLON || (BABYLON = {}));
  87210. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87211. /**
  87212. * Module Debug contains the (visual) components to debug a scene correctly
  87213. */
  87214. var BABYLON;
  87215. (function (BABYLON) {
  87216. var Debug;
  87217. (function (Debug) {
  87218. /**
  87219. * The Axes viewer will show 3 axes in a specific point in space
  87220. */
  87221. var AxesViewer = /** @class */ (function () {
  87222. /**
  87223. * Creates a new AxesViewer
  87224. * @param scene defines the hosting scene
  87225. * @param scaleLines defines a number used to scale line length (1 by default)
  87226. */
  87227. function AxesViewer(scene, scaleLines) {
  87228. if (scaleLines === void 0) { scaleLines = 1; }
  87229. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87230. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87231. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87232. /**
  87233. * Gets or sets a number used to scale line length
  87234. */
  87235. this.scaleLines = 1;
  87236. this.scaleLines = scaleLines;
  87237. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87238. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87239. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87240. this._xmesh.renderingGroupId = 2;
  87241. this._ymesh.renderingGroupId = 2;
  87242. this._zmesh.renderingGroupId = 2;
  87243. this._xmesh.material.checkReadyOnlyOnce = true;
  87244. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87245. this._ymesh.material.checkReadyOnlyOnce = true;
  87246. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87247. this._zmesh.material.checkReadyOnlyOnce = true;
  87248. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87249. this.scene = scene;
  87250. }
  87251. /**
  87252. * Force the viewer to update
  87253. * @param position defines the position of the viewer
  87254. * @param xaxis defines the x axis of the viewer
  87255. * @param yaxis defines the y axis of the viewer
  87256. * @param zaxis defines the z axis of the viewer
  87257. */
  87258. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87259. var scaleLines = this.scaleLines;
  87260. if (this._xmesh) {
  87261. this._xmesh.position.copyFrom(position);
  87262. }
  87263. if (this._ymesh) {
  87264. this._ymesh.position.copyFrom(position);
  87265. }
  87266. if (this._zmesh) {
  87267. this._zmesh.position.copyFrom(position);
  87268. }
  87269. var point2 = this._xline[1];
  87270. point2.x = xaxis.x * scaleLines;
  87271. point2.y = xaxis.y * scaleLines;
  87272. point2.z = xaxis.z * scaleLines;
  87273. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87274. point2 = this._yline[1];
  87275. point2.x = yaxis.x * scaleLines;
  87276. point2.y = yaxis.y * scaleLines;
  87277. point2.z = yaxis.z * scaleLines;
  87278. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87279. point2 = this._zline[1];
  87280. point2.x = zaxis.x * scaleLines;
  87281. point2.y = zaxis.y * scaleLines;
  87282. point2.z = zaxis.z * scaleLines;
  87283. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87284. };
  87285. /** Releases resources */
  87286. AxesViewer.prototype.dispose = function () {
  87287. if (this._xmesh) {
  87288. this._xmesh.dispose();
  87289. }
  87290. if (this._ymesh) {
  87291. this._ymesh.dispose();
  87292. }
  87293. if (this._zmesh) {
  87294. this._zmesh.dispose();
  87295. }
  87296. this._xmesh = null;
  87297. this._ymesh = null;
  87298. this._zmesh = null;
  87299. this.scene = null;
  87300. };
  87301. return AxesViewer;
  87302. }());
  87303. Debug.AxesViewer = AxesViewer;
  87304. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87305. })(BABYLON || (BABYLON = {}));
  87306. //# sourceMappingURL=babylon.axesViewer.js.map
  87307. var BABYLON;
  87308. (function (BABYLON) {
  87309. var Debug;
  87310. (function (Debug) {
  87311. /**
  87312. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87313. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87314. */
  87315. var BoneAxesViewer = /** @class */ (function (_super) {
  87316. __extends(BoneAxesViewer, _super);
  87317. /**
  87318. * Creates a new BoneAxesViewer
  87319. * @param scene defines the hosting scene
  87320. * @param bone defines the target bone
  87321. * @param mesh defines the target mesh
  87322. * @param scaleLines defines a scaling factor for line length (1 by default)
  87323. */
  87324. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87325. if (scaleLines === void 0) { scaleLines = 1; }
  87326. var _this = _super.call(this, scene, scaleLines) || this;
  87327. /** Gets current position */
  87328. _this.pos = BABYLON.Vector3.Zero();
  87329. /** Gets direction of X axis */
  87330. _this.xaxis = BABYLON.Vector3.Zero();
  87331. /** Gets direction of Y axis */
  87332. _this.yaxis = BABYLON.Vector3.Zero();
  87333. /** Gets direction of Z axis */
  87334. _this.zaxis = BABYLON.Vector3.Zero();
  87335. _this.mesh = mesh;
  87336. _this.bone = bone;
  87337. return _this;
  87338. }
  87339. /**
  87340. * Force the viewer to update
  87341. */
  87342. BoneAxesViewer.prototype.update = function () {
  87343. if (!this.mesh || !this.bone) {
  87344. return;
  87345. }
  87346. var bone = this.bone;
  87347. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87348. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87349. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87350. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87351. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87352. };
  87353. /** Releases resources */
  87354. BoneAxesViewer.prototype.dispose = function () {
  87355. if (this.mesh) {
  87356. this.mesh = null;
  87357. this.bone = null;
  87358. _super.prototype.dispose.call(this);
  87359. }
  87360. };
  87361. return BoneAxesViewer;
  87362. }(Debug.AxesViewer));
  87363. Debug.BoneAxesViewer = BoneAxesViewer;
  87364. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87365. })(BABYLON || (BABYLON = {}));
  87366. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87367. var BABYLON;
  87368. (function (BABYLON) {
  87369. var RayHelper = /** @class */ (function () {
  87370. function RayHelper(ray) {
  87371. this.ray = ray;
  87372. }
  87373. RayHelper.CreateAndShow = function (ray, scene, color) {
  87374. var helper = new RayHelper(ray);
  87375. helper.show(scene, color);
  87376. return helper;
  87377. };
  87378. RayHelper.prototype.show = function (scene, color) {
  87379. if (!this._renderFunction && this.ray) {
  87380. var ray = this.ray;
  87381. this._renderFunction = this._render.bind(this);
  87382. this._scene = scene;
  87383. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87384. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87385. if (this._renderFunction) {
  87386. this._scene.registerBeforeRender(this._renderFunction);
  87387. }
  87388. }
  87389. if (color && this._renderLine) {
  87390. this._renderLine.color.copyFrom(color);
  87391. }
  87392. };
  87393. RayHelper.prototype.hide = function () {
  87394. if (this._renderFunction && this._scene) {
  87395. this._scene.unregisterBeforeRender(this._renderFunction);
  87396. this._scene = null;
  87397. this._renderFunction = null;
  87398. if (this._renderLine) {
  87399. this._renderLine.dispose();
  87400. this._renderLine = null;
  87401. }
  87402. this._renderPoints = [];
  87403. }
  87404. };
  87405. RayHelper.prototype._render = function () {
  87406. var ray = this.ray;
  87407. if (!ray) {
  87408. return;
  87409. }
  87410. var point = this._renderPoints[1];
  87411. var len = Math.min(ray.length, 1000000);
  87412. point.copyFrom(ray.direction);
  87413. point.scaleInPlace(len);
  87414. point.addInPlace(ray.origin);
  87415. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87416. };
  87417. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87418. this._attachedToMesh = mesh;
  87419. var ray = this.ray;
  87420. if (!ray) {
  87421. return;
  87422. }
  87423. if (!ray.direction) {
  87424. ray.direction = BABYLON.Vector3.Zero();
  87425. }
  87426. if (!ray.origin) {
  87427. ray.origin = BABYLON.Vector3.Zero();
  87428. }
  87429. if (length) {
  87430. ray.length = length;
  87431. }
  87432. if (!meshSpaceOrigin) {
  87433. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87434. }
  87435. if (!meshSpaceDirection) {
  87436. // -1 so that this will work with Mesh.lookAt
  87437. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87438. }
  87439. if (!this._meshSpaceDirection) {
  87440. this._meshSpaceDirection = meshSpaceDirection.clone();
  87441. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87442. }
  87443. else {
  87444. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87445. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87446. }
  87447. if (!this._updateToMeshFunction) {
  87448. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87449. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87450. }
  87451. this._updateToMesh();
  87452. };
  87453. RayHelper.prototype.detachFromMesh = function () {
  87454. if (this._attachedToMesh) {
  87455. if (this._updateToMeshFunction) {
  87456. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87457. }
  87458. this._attachedToMesh = null;
  87459. this._updateToMeshFunction = null;
  87460. }
  87461. };
  87462. RayHelper.prototype._updateToMesh = function () {
  87463. var ray = this.ray;
  87464. if (!this._attachedToMesh || !ray) {
  87465. return;
  87466. }
  87467. if (this._attachedToMesh._isDisposed) {
  87468. this.detachFromMesh();
  87469. return;
  87470. }
  87471. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87472. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87473. };
  87474. RayHelper.prototype.dispose = function () {
  87475. this.hide();
  87476. this.detachFromMesh();
  87477. this.ray = null;
  87478. };
  87479. return RayHelper;
  87480. }());
  87481. BABYLON.RayHelper = RayHelper;
  87482. })(BABYLON || (BABYLON = {}));
  87483. //# sourceMappingURL=babylon.rayHelper.js.map
  87484. var BABYLON;
  87485. (function (BABYLON) {
  87486. // load the inspector using require, if not present in the global namespace.
  87487. var DebugLayer = /** @class */ (function () {
  87488. function DebugLayer(scene) {
  87489. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87490. this._scene = scene;
  87491. // load inspector using require, if it doesn't exist on the global namespace.
  87492. }
  87493. /** Creates the inspector window. */
  87494. DebugLayer.prototype._createInspector = function (config) {
  87495. if (config === void 0) { config = {}; }
  87496. var popup = config.popup || false;
  87497. var initialTab = config.initialTab || 0;
  87498. var parentElement = config.parentElement || null;
  87499. if (!this._inspector) {
  87500. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87501. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87502. } // else nothing to do,; instance is already existing
  87503. };
  87504. DebugLayer.prototype.isVisible = function () {
  87505. if (!this._inspector) {
  87506. return false;
  87507. }
  87508. return true;
  87509. };
  87510. DebugLayer.prototype.hide = function () {
  87511. if (this._inspector) {
  87512. try {
  87513. this._inspector.dispose();
  87514. }
  87515. catch (e) {
  87516. // If the inspector has been removed directly from the inspector tool
  87517. }
  87518. this.onPropertyChangedObservable.clear();
  87519. this._inspector = null;
  87520. }
  87521. };
  87522. /**
  87523. *
  87524. * Launch the debugLayer.
  87525. *
  87526. * initialTab:
  87527. * | Value | Tab Name |
  87528. * | --- | --- |
  87529. * | 0 | Scene |
  87530. * | 1 | Console |
  87531. * | 2 | Stats |
  87532. * | 3 | Textures |
  87533. * | 4 | Mesh |
  87534. * | 5 | Light |
  87535. * | 6 | Material |
  87536. * | 7 | GLTF |
  87537. * | 8 | GUI |
  87538. * | 9 | Physics |
  87539. * | 10 | Camera |
  87540. * | 11 | Audio |
  87541. *
  87542. */
  87543. DebugLayer.prototype.show = function (config) {
  87544. if (config === void 0) { config = {}; }
  87545. if (typeof this.BJSINSPECTOR == 'undefined') {
  87546. // Load inspector and add it to the DOM
  87547. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87548. }
  87549. else {
  87550. // Otherwise creates the inspector
  87551. this._createInspector(config);
  87552. this.onPropertyChangedObservable = new BABYLON.Observable();
  87553. }
  87554. };
  87555. /**
  87556. * Gets the active tab
  87557. * @return the index of the active tab or -1 if the inspector is hidden
  87558. */
  87559. DebugLayer.prototype.getActiveTab = function () {
  87560. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87561. };
  87562. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87563. return DebugLayer;
  87564. }());
  87565. BABYLON.DebugLayer = DebugLayer;
  87566. })(BABYLON || (BABYLON = {}));
  87567. //# sourceMappingURL=babylon.debugLayer.js.map
  87568. var BABYLON;
  87569. (function (BABYLON) {
  87570. var Debug;
  87571. (function (Debug) {
  87572. /**
  87573. * Used to show the physics impostor around the specific mesh
  87574. */
  87575. var PhysicsViewer = /** @class */ (function () {
  87576. /**
  87577. * Creates a new PhysicsViewer
  87578. * @param scene defines the hosting scene
  87579. */
  87580. function PhysicsViewer(scene) {
  87581. /** @hidden */
  87582. this._impostors = [];
  87583. /** @hidden */
  87584. this._meshes = [];
  87585. /** @hidden */
  87586. this._numMeshes = 0;
  87587. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87588. var physicEngine = this._scene.getPhysicsEngine();
  87589. if (physicEngine) {
  87590. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87591. }
  87592. }
  87593. /** @hidden */
  87594. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87595. var plugin = this._physicsEnginePlugin;
  87596. for (var i = 0; i < this._numMeshes; i++) {
  87597. var impostor = this._impostors[i];
  87598. if (!impostor) {
  87599. continue;
  87600. }
  87601. if (impostor.isDisposed) {
  87602. this.hideImpostor(this._impostors[i--]);
  87603. }
  87604. else {
  87605. var mesh = this._meshes[i];
  87606. if (mesh && plugin) {
  87607. plugin.syncMeshWithImpostor(mesh, impostor);
  87608. }
  87609. }
  87610. }
  87611. };
  87612. /**
  87613. * Renders a specified physic impostor
  87614. * @param impostor defines the impostor to render
  87615. */
  87616. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87617. if (!this._scene) {
  87618. return;
  87619. }
  87620. for (var i = 0; i < this._numMeshes; i++) {
  87621. if (this._impostors[i] == impostor) {
  87622. return;
  87623. }
  87624. }
  87625. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87626. if (debugMesh) {
  87627. this._impostors[this._numMeshes] = impostor;
  87628. this._meshes[this._numMeshes] = debugMesh;
  87629. if (this._numMeshes === 0) {
  87630. this._renderFunction = this._updateDebugMeshes.bind(this);
  87631. this._scene.registerBeforeRender(this._renderFunction);
  87632. }
  87633. this._numMeshes++;
  87634. }
  87635. };
  87636. /**
  87637. * Hides a specified physic impostor
  87638. * @param impostor defines the impostor to hide
  87639. */
  87640. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87641. if (!impostor || !this._scene) {
  87642. return;
  87643. }
  87644. var removed = false;
  87645. for (var i = 0; i < this._numMeshes; i++) {
  87646. if (this._impostors[i] == impostor) {
  87647. var mesh = this._meshes[i];
  87648. if (!mesh) {
  87649. continue;
  87650. }
  87651. this._scene.removeMesh(mesh);
  87652. mesh.dispose();
  87653. this._numMeshes--;
  87654. if (this._numMeshes > 0) {
  87655. this._meshes[i] = this._meshes[this._numMeshes];
  87656. this._impostors[i] = this._impostors[this._numMeshes];
  87657. this._meshes[this._numMeshes] = null;
  87658. this._impostors[this._numMeshes] = null;
  87659. }
  87660. else {
  87661. this._meshes[0] = null;
  87662. this._impostors[0] = null;
  87663. }
  87664. removed = true;
  87665. break;
  87666. }
  87667. }
  87668. if (removed && this._numMeshes === 0) {
  87669. this._scene.unregisterBeforeRender(this._renderFunction);
  87670. }
  87671. };
  87672. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87673. if (!this._debugMaterial) {
  87674. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87675. this._debugMaterial.wireframe = true;
  87676. }
  87677. return this._debugMaterial;
  87678. };
  87679. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87680. if (!this._debugBoxMesh) {
  87681. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87682. this._debugBoxMesh.renderingGroupId = 1;
  87683. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87684. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87685. scene.removeMesh(this._debugBoxMesh);
  87686. }
  87687. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87688. };
  87689. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87690. if (!this._debugSphereMesh) {
  87691. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87692. this._debugSphereMesh.renderingGroupId = 1;
  87693. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87694. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87695. scene.removeMesh(this._debugSphereMesh);
  87696. }
  87697. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87698. };
  87699. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87700. var mesh = null;
  87701. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87702. mesh = this._getDebugBoxMesh(scene);
  87703. impostor.getBoxSizeToRef(mesh.scaling);
  87704. }
  87705. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87706. mesh = this._getDebugSphereMesh(scene);
  87707. var radius = impostor.getRadius();
  87708. mesh.scaling.x = radius * 2;
  87709. mesh.scaling.y = radius * 2;
  87710. mesh.scaling.z = radius * 2;
  87711. }
  87712. return mesh;
  87713. };
  87714. /** Releases all resources */
  87715. PhysicsViewer.prototype.dispose = function () {
  87716. for (var i = 0; i < this._numMeshes; i++) {
  87717. this.hideImpostor(this._impostors[i]);
  87718. }
  87719. if (this._debugBoxMesh) {
  87720. this._debugBoxMesh.dispose();
  87721. }
  87722. if (this._debugSphereMesh) {
  87723. this._debugSphereMesh.dispose();
  87724. }
  87725. if (this._debugMaterial) {
  87726. this._debugMaterial.dispose();
  87727. }
  87728. this._impostors.length = 0;
  87729. this._scene = null;
  87730. this._physicsEnginePlugin = null;
  87731. };
  87732. return PhysicsViewer;
  87733. }());
  87734. Debug.PhysicsViewer = PhysicsViewer;
  87735. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87736. })(BABYLON || (BABYLON = {}));
  87737. //# sourceMappingURL=babylon.physicsViewer.js.map
  87738. var BABYLON;
  87739. (function (BABYLON) {
  87740. var BoundingBoxRenderer = /** @class */ (function () {
  87741. function BoundingBoxRenderer(scene) {
  87742. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87743. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87744. this.showBackLines = true;
  87745. this.renderList = new BABYLON.SmartArray(32);
  87746. this._vertexBuffers = {};
  87747. this._scene = scene;
  87748. }
  87749. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87750. if (this._colorShader) {
  87751. return;
  87752. }
  87753. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87754. attributes: [BABYLON.VertexBuffer.PositionKind],
  87755. uniforms: ["world", "viewProjection", "color"]
  87756. });
  87757. var engine = this._scene.getEngine();
  87758. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87759. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87760. this._createIndexBuffer();
  87761. };
  87762. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87763. var engine = this._scene.getEngine();
  87764. 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]);
  87765. };
  87766. BoundingBoxRenderer.prototype._rebuild = function () {
  87767. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87768. if (vb) {
  87769. vb._rebuild();
  87770. }
  87771. this._createIndexBuffer();
  87772. };
  87773. BoundingBoxRenderer.prototype.reset = function () {
  87774. this.renderList.reset();
  87775. };
  87776. BoundingBoxRenderer.prototype.render = function () {
  87777. if (this.renderList.length === 0) {
  87778. return;
  87779. }
  87780. this._prepareRessources();
  87781. if (!this._colorShader.isReady()) {
  87782. return;
  87783. }
  87784. var engine = this._scene.getEngine();
  87785. engine.setDepthWrite(false);
  87786. this._colorShader._preBind();
  87787. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87788. var boundingBox = this.renderList.data[boundingBoxIndex];
  87789. var min = boundingBox.minimum;
  87790. var max = boundingBox.maximum;
  87791. var diff = max.subtract(min);
  87792. var median = min.add(diff.scale(0.5));
  87793. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87794. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87795. .multiply(boundingBox.getWorldMatrix());
  87796. // VBOs
  87797. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87798. if (this.showBackLines) {
  87799. // Back
  87800. engine.setDepthFunctionToGreaterOrEqual();
  87801. this._scene.resetCachedMaterial();
  87802. this._colorShader.setColor4("color", this.backColor.toColor4());
  87803. this._colorShader.bind(worldMatrix);
  87804. // Draw order
  87805. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87806. }
  87807. // Front
  87808. engine.setDepthFunctionToLess();
  87809. this._scene.resetCachedMaterial();
  87810. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87811. this._colorShader.bind(worldMatrix);
  87812. // Draw order
  87813. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87814. }
  87815. this._colorShader.unbind();
  87816. engine.setDepthFunctionToLessOrEqual();
  87817. engine.setDepthWrite(true);
  87818. };
  87819. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87820. this._prepareRessources();
  87821. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87822. return;
  87823. }
  87824. var engine = this._scene.getEngine();
  87825. engine.setDepthWrite(false);
  87826. engine.setColorWrite(false);
  87827. this._colorShader._preBind();
  87828. var boundingBox = mesh._boundingInfo.boundingBox;
  87829. var min = boundingBox.minimum;
  87830. var max = boundingBox.maximum;
  87831. var diff = max.subtract(min);
  87832. var median = min.add(diff.scale(0.5));
  87833. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87834. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87835. .multiply(boundingBox.getWorldMatrix());
  87836. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87837. engine.setDepthFunctionToLess();
  87838. this._scene.resetCachedMaterial();
  87839. this._colorShader.bind(worldMatrix);
  87840. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87841. this._colorShader.unbind();
  87842. engine.setDepthFunctionToLessOrEqual();
  87843. engine.setDepthWrite(true);
  87844. engine.setColorWrite(true);
  87845. };
  87846. BoundingBoxRenderer.prototype.dispose = function () {
  87847. if (!this._colorShader) {
  87848. return;
  87849. }
  87850. this.renderList.dispose();
  87851. this._colorShader.dispose();
  87852. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87853. if (buffer) {
  87854. buffer.dispose();
  87855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87856. }
  87857. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87858. };
  87859. return BoundingBoxRenderer;
  87860. }());
  87861. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87862. })(BABYLON || (BABYLON = {}));
  87863. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87864. var BABYLON;
  87865. (function (BABYLON) {
  87866. /**
  87867. * Renders a layer on top of an existing scene
  87868. */
  87869. var UtilityLayerRenderer = /** @class */ (function () {
  87870. /**
  87871. * Instantiates a UtilityLayerRenderer
  87872. * @param originalScene the original scene that will be rendered on top of
  87873. */
  87874. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87875. var _this = this;
  87876. this.originalScene = originalScene;
  87877. this._pointerCaptures = {};
  87878. this._lastPointerEvents = {};
  87879. /**
  87880. * If the utility layer should automatically be rendered on top of existing scene
  87881. */
  87882. this.shouldRender = true;
  87883. /**
  87884. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87885. */
  87886. this.onlyCheckPointerDownEvents = true;
  87887. /**
  87888. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87889. */
  87890. this.processAllEvents = false;
  87891. /**
  87892. * Observable raised when the pointer move from the utility layer scene to the main scene
  87893. */
  87894. this.onPointerOutObservable = new BABYLON.Observable();
  87895. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87896. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87897. originalScene.getEngine().scenes.pop();
  87898. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87899. this.utilityLayerScene.detachControl();
  87900. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87901. if (!_this.processAllEvents) {
  87902. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87903. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87904. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87905. return;
  87906. }
  87907. }
  87908. var pointerEvent = (prePointerInfo.event);
  87909. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87910. return;
  87911. }
  87912. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87913. if (!prePointerInfo.ray && utilityScenePick) {
  87914. prePointerInfo.ray = utilityScenePick.ray;
  87915. }
  87916. // always fire the prepointer oversvable
  87917. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87918. // allow every non pointer down event to flow to the utility layer
  87919. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87920. if (!prePointerInfo.skipOnPointerObservable) {
  87921. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87922. }
  87923. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87924. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87925. }
  87926. return;
  87927. }
  87928. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87929. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87930. if (utilityScenePick && utilityScenePick.hit) {
  87931. if (!prePointerInfo.skipOnPointerObservable) {
  87932. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87933. }
  87934. prePointerInfo.skipOnPointerObservable = true;
  87935. }
  87936. }
  87937. else {
  87938. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87939. var pointerEvent_1 = (prePointerInfo.event);
  87940. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87941. if (originalScenePick && utilityScenePick) {
  87942. // No pick in utility scene
  87943. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  87944. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87945. // We touched an utility mesh present in the main scene
  87946. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87947. prePointerInfo.skipOnPointerObservable = true;
  87948. }
  87949. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87950. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  87951. }
  87952. }
  87953. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87954. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87955. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  87956. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87957. }
  87958. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87959. // We have a pick in both scenes but main is closer than utility
  87960. // We touched an utility mesh present in the main scene
  87961. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87962. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87963. prePointerInfo.skipOnPointerObservable = true;
  87964. }
  87965. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  87966. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87967. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  87968. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  87969. }
  87970. }
  87971. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  87972. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  87973. }
  87974. }
  87975. }
  87976. });
  87977. // Render directly on top of existing scene without clearing
  87978. this.utilityLayerScene.autoClear = false;
  87979. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87980. if (_this.shouldRender) {
  87981. _this.render();
  87982. }
  87983. });
  87984. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87985. _this.dispose();
  87986. });
  87987. this._updateCamera();
  87988. }
  87989. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87990. if (!prePointerInfo.skipOnPointerObservable) {
  87991. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87992. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87993. }
  87994. };
  87995. /**
  87996. * Renders the utility layers scene on top of the original scene
  87997. */
  87998. UtilityLayerRenderer.prototype.render = function () {
  87999. this._updateCamera();
  88000. this.utilityLayerScene.render(false);
  88001. };
  88002. /**
  88003. * Disposes of the renderer
  88004. */
  88005. UtilityLayerRenderer.prototype.dispose = function () {
  88006. this.onPointerOutObservable.clear();
  88007. if (this._afterRenderObserver) {
  88008. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88009. }
  88010. if (this._sceneDisposeObserver) {
  88011. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88012. }
  88013. if (this._originalPointerObserver) {
  88014. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88015. }
  88016. this.utilityLayerScene.dispose();
  88017. };
  88018. UtilityLayerRenderer.prototype._updateCamera = function () {
  88019. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88020. };
  88021. return UtilityLayerRenderer;
  88022. }());
  88023. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88024. })(BABYLON || (BABYLON = {}));
  88025. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88026. //# sourceMappingURL=babylon.behavior.js.map
  88027. var BABYLON;
  88028. (function (BABYLON) {
  88029. /**
  88030. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88031. */
  88032. var PointerDragBehavior = /** @class */ (function () {
  88033. /**
  88034. * Creates a pointer drag behavior that can be attached to a mesh
  88035. * @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)
  88036. */
  88037. function PointerDragBehavior(options) {
  88038. this.options = options;
  88039. /**
  88040. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88041. */
  88042. this.currentDraggingPointerID = -1;
  88043. /**
  88044. * If the behavior is currently in a dragging state
  88045. */
  88046. this.dragging = false;
  88047. /**
  88048. * 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)
  88049. */
  88050. this.dragDeltaRatio = 0.2;
  88051. /**
  88052. * If the drag plane orientation should be updated during the dragging (Default: true)
  88053. */
  88054. this.updateDragPlane = true;
  88055. // Debug mode will display drag planes to help visualize behavior
  88056. this._debugMode = false;
  88057. this._moving = false;
  88058. /**
  88059. * Fires each time the attached mesh is dragged with the pointer
  88060. * * delta between last drag position and current drag position in world space
  88061. * * dragDistance along the drag axis
  88062. * * dragPlaneNormal normal of the current drag plane used during the drag
  88063. * * dragPlanePoint in world space where the drag intersects the drag plane
  88064. */
  88065. this.onDragObservable = new BABYLON.Observable();
  88066. /**
  88067. * Fires each time a drag begins (eg. mouse down on mesh)
  88068. */
  88069. this.onDragStartObservable = new BABYLON.Observable();
  88070. /**
  88071. * Fires each time a drag ends (eg. mouse release after drag)
  88072. */
  88073. this.onDragEndObservable = new BABYLON.Observable();
  88074. /**
  88075. * If the attached mesh should be moved when dragged
  88076. */
  88077. this.moveAttached = true;
  88078. /**
  88079. * If the drag behavior will react to drag events (Default: true)
  88080. */
  88081. this.enabled = true;
  88082. /**
  88083. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88084. */
  88085. this.useObjectOrienationForDragging = true;
  88086. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88087. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88088. // Variables to avoid instantiation in the below method
  88089. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88090. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88091. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88092. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88093. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88094. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88095. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88096. var optionCount = 0;
  88097. if (options === undefined) {
  88098. options = {};
  88099. }
  88100. if (options.dragAxis) {
  88101. optionCount++;
  88102. }
  88103. if (options.dragPlaneNormal) {
  88104. optionCount++;
  88105. }
  88106. if (optionCount > 1) {
  88107. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88108. }
  88109. }
  88110. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88111. /**
  88112. * The name of the behavior
  88113. */
  88114. get: function () {
  88115. return "PointerDrag";
  88116. },
  88117. enumerable: true,
  88118. configurable: true
  88119. });
  88120. /**
  88121. * Initializes the behavior
  88122. */
  88123. PointerDragBehavior.prototype.init = function () { };
  88124. /**
  88125. * Attaches the drag behavior the passed in mesh
  88126. * @param ownerNode The mesh that will be dragged around once attached
  88127. */
  88128. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88129. var _this = this;
  88130. this._scene = ownerNode.getScene();
  88131. this._attachedNode = ownerNode;
  88132. // Initialize drag plane to not interfere with existing scene
  88133. if (!PointerDragBehavior._planeScene) {
  88134. if (this._debugMode) {
  88135. PointerDragBehavior._planeScene = this._scene;
  88136. }
  88137. else {
  88138. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88139. this._scene.getEngine().scenes.pop();
  88140. }
  88141. }
  88142. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88143. // State of the drag
  88144. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88145. var delta = new BABYLON.Vector3(0, 0, 0);
  88146. var dragLength = 0;
  88147. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88148. var pickPredicate = function (m) {
  88149. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88150. };
  88151. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88152. if (!_this.enabled) {
  88153. return;
  88154. }
  88155. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88156. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88157. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88158. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88159. if (pickedPoint) {
  88160. _this.dragging = true;
  88161. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88162. _this.lastDragPosition.copyFrom(pickedPoint);
  88163. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88164. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88165. }
  88166. }
  88167. }
  88168. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88169. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88170. _this.releaseDrag();
  88171. }
  88172. }
  88173. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88174. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88175. _this._moving = true;
  88176. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88177. if (pickedPoint) {
  88178. if (_this.updateDragPlane) {
  88179. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88180. }
  88181. // depending on the drag mode option drag accordingly
  88182. if (_this.options.dragAxis) {
  88183. // Convert local drag axis to world
  88184. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88185. // Project delta drag from the drag plane onto the drag axis
  88186. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88187. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88188. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88189. }
  88190. else {
  88191. dragLength = delta.length();
  88192. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88193. }
  88194. targetPosition.addInPlace(delta);
  88195. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88196. _this.lastDragPosition.copyFrom(pickedPoint);
  88197. }
  88198. }
  88199. }
  88200. });
  88201. this._scene.onBeforeRenderObservable.add(function () {
  88202. if (_this._moving && _this.moveAttached) {
  88203. // Slowly move mesh to avoid jitter
  88204. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88205. _this._tmpVector.scaleInPlace(0.2);
  88206. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88207. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88208. }
  88209. });
  88210. };
  88211. PointerDragBehavior.prototype.releaseDrag = function () {
  88212. this.dragging = false;
  88213. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88214. this.currentDraggingPointerID = -1;
  88215. this._moving = false;
  88216. };
  88217. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88218. var _this = this;
  88219. if (!ray) {
  88220. return null;
  88221. }
  88222. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88223. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88224. return pickResult.pickedPoint;
  88225. }
  88226. else {
  88227. return null;
  88228. }
  88229. };
  88230. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88231. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88232. this._pointA.copyFrom(dragPlanePosition);
  88233. if (this.options.dragAxis) {
  88234. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88235. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88236. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88237. ray.origin.subtractToRef(this._pointA, this._pointC);
  88238. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88239. // Get perpendicular line from direction to camera and drag axis
  88240. this._pointB.subtractToRef(this._pointA, this._lineA);
  88241. this._pointC.subtractToRef(this._pointA, this._lineB);
  88242. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88243. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88244. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88245. this._lookAt.normalize();
  88246. this._dragPlane.position.copyFrom(this._pointA);
  88247. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88248. this._dragPlane.lookAt(this._lookAt);
  88249. }
  88250. else if (this.options.dragPlaneNormal) {
  88251. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88252. this._dragPlane.position.copyFrom(this._pointA);
  88253. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88254. this._dragPlane.lookAt(this._lookAt);
  88255. }
  88256. else {
  88257. this._dragPlane.position.copyFrom(this._pointA);
  88258. this._dragPlane.lookAt(ray.origin);
  88259. }
  88260. this._dragPlane.computeWorldMatrix(true);
  88261. };
  88262. /**
  88263. * Detaches the behavior from the mesh
  88264. */
  88265. PointerDragBehavior.prototype.detach = function () {
  88266. if (this._pointerObserver) {
  88267. this._scene.onPointerObservable.remove(this._pointerObserver);
  88268. }
  88269. };
  88270. return PointerDragBehavior;
  88271. }());
  88272. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88273. })(BABYLON || (BABYLON = {}));
  88274. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88275. var BABYLON;
  88276. (function (BABYLON) {
  88277. /**
  88278. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88279. */
  88280. var MultiPointerScaleBehavior = /** @class */ (function () {
  88281. function MultiPointerScaleBehavior() {
  88282. this._startDistance = 0;
  88283. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88284. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88285. this._sceneRenderObserver = null;
  88286. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88287. this._dragBehaviorA.moveAttached = false;
  88288. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88289. this._dragBehaviorB.moveAttached = false;
  88290. }
  88291. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88292. /**
  88293. * The name of the behavior
  88294. */
  88295. get: function () {
  88296. return "MultiPointerScale";
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. /**
  88302. * Initializes the behavior
  88303. */
  88304. MultiPointerScaleBehavior.prototype.init = function () { };
  88305. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88306. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88307. };
  88308. /**
  88309. * Attaches the scale behavior the passed in mesh
  88310. * @param ownerNode The mesh that will be scaled around once attached
  88311. */
  88312. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88313. var _this = this;
  88314. this._ownerNode = ownerNode;
  88315. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88316. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88317. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88318. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88319. _this._dragBehaviorA.releaseDrag();
  88320. }
  88321. else {
  88322. _this._initialScale.copyFrom(ownerNode.scaling);
  88323. _this._startDistance = _this._getCurrentDistance();
  88324. }
  88325. }
  88326. });
  88327. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88328. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88329. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88330. _this._dragBehaviorB.releaseDrag();
  88331. }
  88332. else {
  88333. _this._initialScale.copyFrom(ownerNode.scaling);
  88334. _this._startDistance = _this._getCurrentDistance();
  88335. }
  88336. }
  88337. });
  88338. // Once both drag behaviors are active scale based on the distance between the two pointers
  88339. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88340. behavior.onDragObservable.add(function () {
  88341. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88342. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88343. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88344. }
  88345. });
  88346. });
  88347. ownerNode.addBehavior(this._dragBehaviorA);
  88348. ownerNode.addBehavior(this._dragBehaviorB);
  88349. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88350. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88351. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88352. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88353. if (change.length() > 0.01) {
  88354. ownerNode.scaling.addInPlace(change);
  88355. }
  88356. }
  88357. });
  88358. };
  88359. /**
  88360. * Detaches the behavior from the mesh
  88361. */
  88362. MultiPointerScaleBehavior.prototype.detach = function () {
  88363. var _this = this;
  88364. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88365. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88366. behavior.onDragStartObservable.clear();
  88367. behavior.onDragObservable.clear();
  88368. _this._ownerNode.removeBehavior(behavior);
  88369. });
  88370. };
  88371. return MultiPointerScaleBehavior;
  88372. }());
  88373. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88374. })(BABYLON || (BABYLON = {}));
  88375. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88376. var BABYLON;
  88377. (function (BABYLON) {
  88378. /**
  88379. * 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
  88380. */
  88381. var SixDofDragBehavior = /** @class */ (function () {
  88382. function SixDofDragBehavior() {
  88383. this._sceneRenderObserver = null;
  88384. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88385. this._moving = false;
  88386. this._startingOrientation = new BABYLON.Quaternion();
  88387. /**
  88388. * 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: 5)
  88389. */
  88390. this.zDragFactor = 5;
  88391. /**
  88392. * If the behavior is currently in a dragging state
  88393. */
  88394. this.dragging = false;
  88395. /**
  88396. * 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)
  88397. */
  88398. this.dragDeltaRatio = 0.2;
  88399. /**
  88400. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88401. */
  88402. this.currentDraggingPointerID = -1;
  88403. }
  88404. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88405. /**
  88406. * The name of the behavior
  88407. */
  88408. get: function () {
  88409. return "SixDofDrag";
  88410. },
  88411. enumerable: true,
  88412. configurable: true
  88413. });
  88414. /**
  88415. * Initializes the behavior
  88416. */
  88417. SixDofDragBehavior.prototype.init = function () { };
  88418. /**
  88419. * Attaches the scale behavior the passed in mesh
  88420. * @param ownerNode The mesh that will be scaled around once attached
  88421. */
  88422. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88423. var _this = this;
  88424. this._ownerNode = ownerNode;
  88425. this._scene = this._ownerNode.getScene();
  88426. if (!SixDofDragBehavior._virtualScene) {
  88427. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88428. this._scene.getEngine().scenes.pop();
  88429. }
  88430. var pickedMesh = null;
  88431. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88432. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88433. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88434. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88435. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88436. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88437. var pickPredicate = function (m) {
  88438. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88439. };
  88440. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88441. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88442. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88443. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88444. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88445. // Set position and orientation of the controller
  88446. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88447. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88448. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88449. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88450. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88451. if (!pickedMesh.rotationQuaternion) {
  88452. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88453. }
  88454. var oldParent = pickedMesh.parent;
  88455. pickedMesh.setParent(null);
  88456. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88457. pickedMesh.setParent(oldParent);
  88458. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88459. // Update state
  88460. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88461. _this.dragging = true;
  88462. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88463. }
  88464. }
  88465. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88466. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88467. _this.dragging = false;
  88468. _this._moving = false;
  88469. _this.currentDraggingPointerID = -1;
  88470. pickedMesh = null;
  88471. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88472. }
  88473. }
  88474. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88475. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88476. // Calculate controller drag distance in controller space
  88477. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88478. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88479. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88480. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88481. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88482. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88483. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88484. if (_this._virtualDragMesh.position.z < 0) {
  88485. _this._virtualDragMesh.position.z = 0;
  88486. }
  88487. // Update the controller position
  88488. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88489. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88490. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88491. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88492. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88493. if (pickedMesh.parent) {
  88494. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88495. }
  88496. if (!_this._moving) {
  88497. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88498. }
  88499. _this._moving = true;
  88500. }
  88501. }
  88502. });
  88503. var tmpQuaternion = new BABYLON.Quaternion();
  88504. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88505. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88506. if (_this.dragging && _this._moving && pickedMesh) {
  88507. // Slowly move mesh to avoid jitter
  88508. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88509. // Get change in rotation
  88510. tmpQuaternion.copyFrom(_this._startingOrientation);
  88511. tmpQuaternion.x = -tmpQuaternion.x;
  88512. tmpQuaternion.y = -tmpQuaternion.y;
  88513. tmpQuaternion.z = -tmpQuaternion.z;
  88514. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88515. // Convert change in rotation to only y axis rotation
  88516. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88517. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88518. // Slowly move mesh to avoid jitter
  88519. var oldParent = pickedMesh.parent;
  88520. pickedMesh.setParent(null);
  88521. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88522. pickedMesh.setParent(oldParent);
  88523. }
  88524. });
  88525. };
  88526. /**
  88527. * Detaches the behavior from the mesh
  88528. */
  88529. SixDofDragBehavior.prototype.detach = function () {
  88530. this._scene.onPointerObservable.remove(this._pointerObserver);
  88531. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88532. this._virtualOriginMesh.dispose();
  88533. this._virtualDragMesh.dispose();
  88534. };
  88535. return SixDofDragBehavior;
  88536. }());
  88537. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88538. })(BABYLON || (BABYLON = {}));
  88539. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88540. var BABYLON;
  88541. (function (BABYLON) {
  88542. /**
  88543. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88544. */
  88545. var Gizmo = /** @class */ (function () {
  88546. /**
  88547. * Creates a gizmo
  88548. * @param gizmoLayer The utility layer the gizmo will be added to
  88549. */
  88550. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88551. var _this = this;
  88552. this.gizmoLayer = gizmoLayer;
  88553. /**
  88554. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88555. */
  88556. this.updateGizmoRotationToMatchAttachedMesh = true;
  88557. /**
  88558. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88559. */
  88560. this.updateGizmoPositionToMatchAttachedMesh = true;
  88561. /**
  88562. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88563. */
  88564. this._updateScale = true;
  88565. this._interactionsEnabled = true;
  88566. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88567. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88568. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88569. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88570. _this._rootMesh.scaling.set(dist, dist, dist);
  88571. }
  88572. if (_this.attachedMesh) {
  88573. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88574. if (!_this._rootMesh.rotationQuaternion) {
  88575. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88576. }
  88577. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88578. }
  88579. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88580. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88581. }
  88582. }
  88583. });
  88584. }
  88585. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88586. };
  88587. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88588. get: function () {
  88589. return this._interactionsEnabled;
  88590. },
  88591. /**
  88592. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88593. */
  88594. set: function (value) {
  88595. this._interactionsEnabled = value;
  88596. this._onInteractionsEnabledChanged(value);
  88597. },
  88598. enumerable: true,
  88599. configurable: true
  88600. });
  88601. /**
  88602. * Disposes of the gizmo
  88603. */
  88604. Gizmo.prototype.dispose = function () {
  88605. this._rootMesh.dispose();
  88606. if (this._beforeRenderObserver) {
  88607. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88608. }
  88609. };
  88610. return Gizmo;
  88611. }());
  88612. BABYLON.Gizmo = Gizmo;
  88613. })(BABYLON || (BABYLON = {}));
  88614. //# sourceMappingURL=babylon.gizmo.js.map
  88615. var BABYLON;
  88616. (function (BABYLON) {
  88617. /**
  88618. * Single axis drag gizmo
  88619. */
  88620. var AxisDragGizmo = /** @class */ (function (_super) {
  88621. __extends(AxisDragGizmo, _super);
  88622. /**
  88623. * Creates an AxisDragGizmo
  88624. * @param gizmoLayer The utility layer the gizmo will be added to
  88625. * @param dragAxis The axis which the gizmo will be able to drag on
  88626. * @param color The color of the gizmo
  88627. */
  88628. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88629. var _this = _super.call(this, gizmoLayer) || this;
  88630. _this._pointerObserver = null;
  88631. // Create Material
  88632. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88633. coloredMaterial.disableLighting = true;
  88634. coloredMaterial.emissiveColor = color;
  88635. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88636. hoverMaterial.disableLighting = true;
  88637. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88638. // Build mesh on root node
  88639. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88640. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88641. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88642. arrow.addChild(arrowMesh);
  88643. arrow.addChild(arrowTail);
  88644. // Position arrow pointing in its drag axis
  88645. arrowMesh.scaling.scaleInPlace(0.05);
  88646. arrowMesh.material = coloredMaterial;
  88647. arrowMesh.rotation.x = Math.PI / 2;
  88648. arrowMesh.position.z += 0.3;
  88649. arrowTail.rotation.x = Math.PI / 2;
  88650. arrowTail.material = coloredMaterial;
  88651. arrowTail.position.z += 0.15;
  88652. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88653. _this._rootMesh.addChild(arrow);
  88654. // Add drag behavior to handle events when the gizmo is dragged
  88655. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88656. _this._dragBehavior.moveAttached = false;
  88657. _this._rootMesh.addBehavior(_this._dragBehavior);
  88658. _this._dragBehavior.onDragObservable.add(function (event) {
  88659. if (!_this.interactionsEnabled) {
  88660. return;
  88661. }
  88662. if (_this.attachedMesh) {
  88663. _this.attachedMesh.position.addInPlace(event.delta);
  88664. }
  88665. });
  88666. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88667. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88668. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88669. m.material = hoverMaterial;
  88670. });
  88671. }
  88672. else {
  88673. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88674. m.material = coloredMaterial;
  88675. });
  88676. }
  88677. });
  88678. return _this;
  88679. }
  88680. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88681. this._dragBehavior.enabled = value;
  88682. };
  88683. /**
  88684. * Disposes of the gizmo
  88685. */
  88686. AxisDragGizmo.prototype.dispose = function () {
  88687. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88688. this._dragBehavior.detach();
  88689. _super.prototype.dispose.call(this);
  88690. };
  88691. return AxisDragGizmo;
  88692. }(BABYLON.Gizmo));
  88693. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88694. })(BABYLON || (BABYLON = {}));
  88695. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88696. var BABYLON;
  88697. (function (BABYLON) {
  88698. /**
  88699. * Single axis scale gizmo
  88700. */
  88701. var AxisScaleGizmo = /** @class */ (function (_super) {
  88702. __extends(AxisScaleGizmo, _super);
  88703. /**
  88704. * Creates an AxisScaleGizmo
  88705. * @param gizmoLayer The utility layer the gizmo will be added to
  88706. * @param dragAxis The axis which the gizmo will be able to scale on
  88707. * @param color The color of the gizmo
  88708. */
  88709. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88710. var _this = _super.call(this, gizmoLayer) || this;
  88711. _this._pointerObserver = null;
  88712. // Create Material
  88713. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88714. coloredMaterial.disableLighting = true;
  88715. coloredMaterial.emissiveColor = color;
  88716. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88717. hoverMaterial.disableLighting = true;
  88718. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88719. // Build mesh on root node
  88720. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88721. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  88722. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88723. arrow.addChild(arrowMesh);
  88724. arrow.addChild(arrowTail);
  88725. // Position arrow pointing in its drag axis
  88726. arrowMesh.scaling.scaleInPlace(0.1);
  88727. arrowMesh.material = coloredMaterial;
  88728. arrowMesh.rotation.x = Math.PI / 2;
  88729. arrowMesh.position.z += 0.3;
  88730. arrowTail.rotation.x = Math.PI / 2;
  88731. arrowTail.material = coloredMaterial;
  88732. arrowTail.position.z += 0.15;
  88733. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88734. _this._rootMesh.addChild(arrow);
  88735. // Add drag behavior to handle events when the gizmo is dragged
  88736. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88737. _this._dragBehavior.moveAttached = false;
  88738. _this._rootMesh.addBehavior(_this._dragBehavior);
  88739. var tmpVector = new BABYLON.Vector3();
  88740. _this._dragBehavior.onDragObservable.add(function (event) {
  88741. if (!_this.interactionsEnabled) {
  88742. return;
  88743. }
  88744. if (_this.attachedMesh) {
  88745. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  88746. var invertCount = 0;
  88747. if (_this.attachedMesh.scaling["x"] < 0) {
  88748. invertCount++;
  88749. }
  88750. if (_this.attachedMesh.scaling["y"] < 0) {
  88751. invertCount++;
  88752. }
  88753. if (_this.attachedMesh.scaling["z"] < 0) {
  88754. invertCount++;
  88755. }
  88756. if (invertCount % 2 == 0) {
  88757. _this.attachedMesh.scaling.addInPlace(tmpVector);
  88758. }
  88759. else {
  88760. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  88761. }
  88762. }
  88763. });
  88764. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88765. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88766. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88767. m.material = hoverMaterial;
  88768. });
  88769. }
  88770. else {
  88771. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88772. m.material = coloredMaterial;
  88773. });
  88774. }
  88775. });
  88776. return _this;
  88777. }
  88778. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88779. this._dragBehavior.enabled = value;
  88780. };
  88781. /**
  88782. * Disposes of the gizmo
  88783. */
  88784. AxisScaleGizmo.prototype.dispose = function () {
  88785. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88786. this._dragBehavior.detach();
  88787. _super.prototype.dispose.call(this);
  88788. };
  88789. return AxisScaleGizmo;
  88790. }(BABYLON.Gizmo));
  88791. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88792. })(BABYLON || (BABYLON = {}));
  88793. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88794. var BABYLON;
  88795. (function (BABYLON) {
  88796. /**
  88797. * Single plane rotation gizmo
  88798. */
  88799. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88800. __extends(PlaneRotationGizmo, _super);
  88801. /**
  88802. * Creates a PlaneRotationGizmo
  88803. * @param gizmoLayer The utility layer the gizmo will be added to
  88804. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88805. * @param color The color of the gizmo
  88806. */
  88807. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88808. var _this = _super.call(this, gizmoLayer) || this;
  88809. _this._pointerObserver = null;
  88810. // Create Material
  88811. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88812. coloredMaterial.disableLighting = true;
  88813. coloredMaterial.emissiveColor = color;
  88814. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88815. hoverMaterial.disableLighting = true;
  88816. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88817. // Build mesh on root node
  88818. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88819. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  88820. // Position arrow pointing in its drag axis
  88821. rotationMesh.scaling.scaleInPlace(0.1);
  88822. rotationMesh.material = coloredMaterial;
  88823. rotationMesh.rotation.x = Math.PI / 2;
  88824. parentMesh.addChild(rotationMesh);
  88825. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88826. _this._rootMesh.addChild(parentMesh);
  88827. // Add drag behavior to handle events when the gizmo is dragged
  88828. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  88829. _this._dragBehavior.moveAttached = false;
  88830. _this._rootMesh.addBehavior(_this._dragBehavior);
  88831. var lastDragPosition = null;
  88832. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88833. if (!_this.interactionsEnabled) {
  88834. return;
  88835. }
  88836. lastDragPosition = e.dragPlanePoint;
  88837. });
  88838. var rotationMatrix = new BABYLON.Matrix();
  88839. var planeNormalTowardsCamera = new BABYLON.Vector3();
  88840. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  88841. _this._dragBehavior.onDragObservable.add(function (event) {
  88842. if (!_this.interactionsEnabled) {
  88843. return;
  88844. }
  88845. if (_this.attachedMesh && lastDragPosition) {
  88846. if (!_this.attachedMesh.rotationQuaternion) {
  88847. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88848. }
  88849. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88850. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88851. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88852. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88853. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88854. var angle = Math.atan2(cross.length(), dot);
  88855. planeNormalTowardsCamera.copyFrom(planeNormal);
  88856. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  88857. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88858. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  88859. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  88860. }
  88861. // Flip up vector depending on which side the camera is on
  88862. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88863. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88864. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  88865. planeNormalTowardsCamera.scaleInPlace(-1);
  88866. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  88867. }
  88868. }
  88869. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  88870. if (halfCircleSide)
  88871. angle = -angle;
  88872. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88873. var quaternionCoefficient = Math.sin(angle / 2);
  88874. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  88875. // Rotate selected mesh quaternion over fixed axis
  88876. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  88877. lastDragPosition = event.dragPlanePoint;
  88878. }
  88879. });
  88880. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88881. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88882. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88883. m.material = hoverMaterial;
  88884. });
  88885. }
  88886. else {
  88887. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88888. m.material = coloredMaterial;
  88889. });
  88890. }
  88891. });
  88892. return _this;
  88893. }
  88894. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88895. this._dragBehavior.enabled = value;
  88896. };
  88897. /**
  88898. * Disposes of the gizmo
  88899. */
  88900. PlaneRotationGizmo.prototype.dispose = function () {
  88901. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88902. this._dragBehavior.detach();
  88903. _super.prototype.dispose.call(this);
  88904. };
  88905. return PlaneRotationGizmo;
  88906. }(BABYLON.Gizmo));
  88907. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88908. })(BABYLON || (BABYLON = {}));
  88909. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88910. var BABYLON;
  88911. (function (BABYLON) {
  88912. /**
  88913. * Gizmo that enables dragging a mesh along 3 axis
  88914. */
  88915. var PositionGizmo = /** @class */ (function (_super) {
  88916. __extends(PositionGizmo, _super);
  88917. /**
  88918. * Creates a PositionGizmo
  88919. * @param gizmoLayer The utility layer the gizmo will be added to
  88920. */
  88921. function PositionGizmo(gizmoLayer) {
  88922. var _this = _super.call(this, gizmoLayer) || this;
  88923. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  88924. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  88925. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  88926. return _this;
  88927. }
  88928. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88929. set: function (mesh) {
  88930. this._xDrag.attachedMesh = mesh;
  88931. this._yDrag.attachedMesh = mesh;
  88932. this._zDrag.attachedMesh = mesh;
  88933. },
  88934. enumerable: true,
  88935. configurable: true
  88936. });
  88937. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88938. this._xDrag.interactionsEnabled = value;
  88939. this._yDrag.interactionsEnabled = value;
  88940. this._zDrag.interactionsEnabled = value;
  88941. };
  88942. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  88943. get: function () {
  88944. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  88945. },
  88946. set: function (value) {
  88947. if (this._xDrag) {
  88948. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  88949. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  88950. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  88951. }
  88952. },
  88953. enumerable: true,
  88954. configurable: true
  88955. });
  88956. /**
  88957. * Disposes of the gizmo
  88958. */
  88959. PositionGizmo.prototype.dispose = function () {
  88960. this._xDrag.dispose();
  88961. this._yDrag.dispose();
  88962. this._zDrag.dispose();
  88963. };
  88964. return PositionGizmo;
  88965. }(BABYLON.Gizmo));
  88966. BABYLON.PositionGizmo = PositionGizmo;
  88967. })(BABYLON || (BABYLON = {}));
  88968. //# sourceMappingURL=babylon.positionGizmo.js.map
  88969. var BABYLON;
  88970. (function (BABYLON) {
  88971. /**
  88972. * Gizmo that enables rotating a mesh along 3 axis
  88973. */
  88974. var RotationGizmo = /** @class */ (function (_super) {
  88975. __extends(RotationGizmo, _super);
  88976. /**
  88977. * Creates a RotationGizmo
  88978. * @param gizmoLayer The utility layer the gizmo will be added to
  88979. */
  88980. function RotationGizmo(gizmoLayer) {
  88981. var _this = _super.call(this, gizmoLayer) || this;
  88982. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  88983. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  88984. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  88985. return _this;
  88986. }
  88987. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88988. set: function (mesh) {
  88989. this._xDrag.attachedMesh = mesh;
  88990. this._yDrag.attachedMesh = mesh;
  88991. this._zDrag.attachedMesh = mesh;
  88992. },
  88993. enumerable: true,
  88994. configurable: true
  88995. });
  88996. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88997. this._xDrag.interactionsEnabled = value;
  88998. this._yDrag.interactionsEnabled = value;
  88999. this._zDrag.interactionsEnabled = value;
  89000. };
  89001. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89002. get: function () {
  89003. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89004. },
  89005. set: function (value) {
  89006. if (this._xDrag) {
  89007. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89008. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89009. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89010. }
  89011. },
  89012. enumerable: true,
  89013. configurable: true
  89014. });
  89015. /**
  89016. * Disposes of the gizmo
  89017. */
  89018. RotationGizmo.prototype.dispose = function () {
  89019. this._xDrag.dispose();
  89020. this._yDrag.dispose();
  89021. this._zDrag.dispose();
  89022. };
  89023. return RotationGizmo;
  89024. }(BABYLON.Gizmo));
  89025. BABYLON.RotationGizmo = RotationGizmo;
  89026. })(BABYLON || (BABYLON = {}));
  89027. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89028. var BABYLON;
  89029. (function (BABYLON) {
  89030. /**
  89031. * Gizmo that enables scaling a mesh along 3 axis
  89032. */
  89033. var ScaleGizmo = /** @class */ (function (_super) {
  89034. __extends(ScaleGizmo, _super);
  89035. /**
  89036. * Creates a ScaleGizmo
  89037. * @param gizmoLayer The utility layer the gizmo will be added to
  89038. */
  89039. function ScaleGizmo(gizmoLayer) {
  89040. var _this = _super.call(this, gizmoLayer) || this;
  89041. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89042. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89043. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89044. return _this;
  89045. }
  89046. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89047. set: function (mesh) {
  89048. this._xDrag.attachedMesh = mesh;
  89049. this._yDrag.attachedMesh = mesh;
  89050. this._zDrag.attachedMesh = mesh;
  89051. },
  89052. enumerable: true,
  89053. configurable: true
  89054. });
  89055. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  89056. this._xDrag.interactionsEnabled = value;
  89057. this._yDrag.interactionsEnabled = value;
  89058. this._zDrag.interactionsEnabled = value;
  89059. };
  89060. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89061. get: function () {
  89062. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89063. },
  89064. set: function (value) {
  89065. if (this._xDrag) {
  89066. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89067. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89068. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89069. }
  89070. },
  89071. enumerable: true,
  89072. configurable: true
  89073. });
  89074. /**
  89075. * Disposes of the gizmo
  89076. */
  89077. ScaleGizmo.prototype.dispose = function () {
  89078. this._xDrag.dispose();
  89079. this._yDrag.dispose();
  89080. this._zDrag.dispose();
  89081. };
  89082. return ScaleGizmo;
  89083. }(BABYLON.Gizmo));
  89084. BABYLON.ScaleGizmo = ScaleGizmo;
  89085. })(BABYLON || (BABYLON = {}));
  89086. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89087. var BABYLON;
  89088. (function (BABYLON) {
  89089. /**
  89090. * Bounding box gizmo
  89091. */
  89092. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89093. __extends(BoundingBoxGizmo, _super);
  89094. /**
  89095. * Creates an BoundingBoxGizmo
  89096. * @param gizmoLayer The utility layer the gizmo will be added to
  89097. * @param color The color of the gizmo
  89098. */
  89099. function BoundingBoxGizmo(gizmoLayer, color) {
  89100. var _this = _super.call(this, gizmoLayer) || this;
  89101. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89102. _this._renderObserver = null;
  89103. _this._pointerObserver = null;
  89104. _this._scaleDragSpeed = 0.2;
  89105. _this._tmpQuaternion = new BABYLON.Quaternion();
  89106. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89107. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89108. _this._updateScale = false;
  89109. // Create Materials
  89110. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89111. coloredMaterial.disableLighting = true;
  89112. coloredMaterial.emissiveColor = color;
  89113. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89114. hoverColoredMaterial.disableLighting = true;
  89115. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89116. // Build bounding box out of lines
  89117. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89118. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89119. var lines = [];
  89120. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89121. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89122. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89123. 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));
  89124. 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));
  89125. 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));
  89126. 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));
  89127. 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));
  89128. 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));
  89129. 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));
  89130. 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));
  89131. 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));
  89132. lines.forEach(function (l) {
  89133. l.color = color;
  89134. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89135. l.isPickable = false;
  89136. _this._lineBoundingBox.addChild(l);
  89137. });
  89138. _this._rootMesh.addChild(_this._lineBoundingBox);
  89139. // Create rotation spheres
  89140. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89141. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89142. var _loop_1 = function (i_1) {
  89143. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  89144. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89145. sphere.material = coloredMaterial;
  89146. // Drag behavior
  89147. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89148. _dragBehavior.moveAttached = false;
  89149. _dragBehavior.updateDragPlane = false;
  89150. sphere.addBehavior(_dragBehavior);
  89151. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89152. var totalTurnAmountOfDrag = 0;
  89153. _dragBehavior.onDragStartObservable.add(function (event) {
  89154. startingTurnDirection.copyFrom(sphere.forward);
  89155. totalTurnAmountOfDrag = 0;
  89156. });
  89157. _dragBehavior.onDragObservable.add(function (event) {
  89158. if (_this.attachedMesh) {
  89159. var worldDragDirection = startingTurnDirection;
  89160. // Project the world right on to the drag plane
  89161. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89162. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89163. // project drag delta on to the resulting drag axis and rotate based on that
  89164. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89165. // Rotate based on axis
  89166. if (!_this.attachedMesh.rotationQuaternion) {
  89167. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89168. }
  89169. // Do not allow the object to turn more than a full circle
  89170. totalTurnAmountOfDrag += projectDist;
  89171. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89172. if (i_1 >= 8) {
  89173. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89174. }
  89175. else if (i_1 >= 4) {
  89176. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89177. }
  89178. else {
  89179. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89180. }
  89181. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89182. }
  89183. }
  89184. });
  89185. // Selection/deselection
  89186. _dragBehavior.onDragStartObservable.add(function () {
  89187. _this._selectNode(sphere);
  89188. });
  89189. _dragBehavior.onDragEndObservable.add(function () {
  89190. _this._selectNode(null);
  89191. });
  89192. this_1._rotateSpheresParent.addChild(sphere);
  89193. };
  89194. var this_1 = this, _dragBehavior;
  89195. for (var i_1 = 0; i_1 < 12; i_1++) {
  89196. _loop_1(i_1);
  89197. }
  89198. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89199. // Create scale cubes
  89200. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89201. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89202. for (var i = 0; i < 2; i++) {
  89203. for (var j = 0; j < 2; j++) {
  89204. var _loop_2 = function () {
  89205. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89206. box.material = coloredMaterial;
  89207. // Dragging logic
  89208. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89209. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89210. _dragBehavior.moveAttached = false;
  89211. box.addBehavior(_dragBehavior);
  89212. _dragBehavior.onDragObservable.add(function (event) {
  89213. if (_this.attachedMesh) {
  89214. // Current boudning box dimensions
  89215. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89216. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89217. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89218. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89219. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89220. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89221. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89222. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89223. // Update scale and position
  89224. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89225. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89226. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89227. }
  89228. });
  89229. // Selection/deselection
  89230. _dragBehavior.onDragStartObservable.add(function () {
  89231. _this._selectNode(box);
  89232. });
  89233. _dragBehavior.onDragEndObservable.add(function () {
  89234. _this._selectNode(null);
  89235. });
  89236. this_2._scaleBoxesParent.addChild(box);
  89237. };
  89238. var this_2 = this, _dragBehavior;
  89239. for (var k = 0; k < 2; k++) {
  89240. _loop_2();
  89241. }
  89242. }
  89243. }
  89244. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89245. // Hover color change
  89246. var pointerIds = new Array();
  89247. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89248. if (!pointerIds[pointerInfo.event.pointerId]) {
  89249. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89250. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89251. pointerIds[pointerInfo.event.pointerId] = mesh;
  89252. mesh.material = hoverColoredMaterial;
  89253. }
  89254. });
  89255. }
  89256. else {
  89257. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89258. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89259. delete pointerIds[pointerInfo.event.pointerId];
  89260. }
  89261. }
  89262. });
  89263. // Update bounding box positions
  89264. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89265. _this._updateBoundingBox();
  89266. });
  89267. _this._updateBoundingBox();
  89268. return _this;
  89269. }
  89270. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89271. this._rotateSpheresParent.getChildMeshes()
  89272. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89273. m.isVisible = (!selectedMesh || m == selectedMesh);
  89274. });
  89275. };
  89276. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89277. if (this.attachedMesh) {
  89278. // Update bounding dimensions/positions
  89279. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89280. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89281. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89282. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89283. }
  89284. // Update rotation sphere locations
  89285. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89286. for (var i = 0; i < 3; i++) {
  89287. for (var j = 0; j < 2; j++) {
  89288. for (var k = 0; k < 2; k++) {
  89289. var index = ((i * 4) + (j * 2)) + k;
  89290. if (i == 0) {
  89291. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89292. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89293. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89294. }
  89295. if (i == 1) {
  89296. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89297. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89298. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89299. }
  89300. if (i == 2) {
  89301. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89302. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89303. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89304. }
  89305. }
  89306. }
  89307. }
  89308. // Update scale box locations
  89309. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89310. for (var i = 0; i < 2; i++) {
  89311. for (var j = 0; j < 2; j++) {
  89312. for (var k = 0; k < 2; k++) {
  89313. var index = ((i * 4) + (j * 2)) + k;
  89314. if (scaleBoxes[index]) {
  89315. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89316. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89317. }
  89318. }
  89319. }
  89320. }
  89321. };
  89322. /**
  89323. * Disposes of the gizmo
  89324. */
  89325. BoundingBoxGizmo.prototype.dispose = function () {
  89326. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89327. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89328. this._lineBoundingBox.dispose();
  89329. this._rotateSpheresParent.dispose();
  89330. this._scaleBoxesParent.dispose();
  89331. _super.prototype.dispose.call(this);
  89332. };
  89333. return BoundingBoxGizmo;
  89334. }(BABYLON.Gizmo));
  89335. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89336. })(BABYLON || (BABYLON = {}));
  89337. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89338. var BABYLON;
  89339. (function (BABYLON) {
  89340. /**
  89341. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89342. */
  89343. var GizmoManager = /** @class */ (function () {
  89344. /**
  89345. * Instatiates a gizmo manager
  89346. * @param scene the scene to overlay the gizmos on top of
  89347. * @param options If only a single gizmo should exist at one time
  89348. */
  89349. function GizmoManager(scene, options) {
  89350. var _this = this;
  89351. this.scene = scene;
  89352. // Set of gizmos that are currently in the scene for each mesh
  89353. this._gizmoSet = {};
  89354. this._pointerObserver = null;
  89355. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89356. // Options parsing
  89357. if (!options) {
  89358. options = {};
  89359. }
  89360. if (options.singleGizmo === undefined) {
  89361. options.singleGizmo = true;
  89362. }
  89363. // Instatiate/dispose gizmos based on pointer actions
  89364. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89365. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89366. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89367. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89368. if (options.singleGizmo) {
  89369. _this._clearGizmos();
  89370. }
  89371. // Enable gizmo when mesh is selected
  89372. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89373. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89374. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89375. }
  89376. else {
  89377. if (!options.singleGizmo) {
  89378. // Disable gizmo when clicked again
  89379. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89380. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89381. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89382. }
  89383. }
  89384. }
  89385. else {
  89386. if (options.singleGizmo) {
  89387. // Disable gizmo when clicked away
  89388. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89389. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89390. if (gizmoPick && !gizmoPick.hit) {
  89391. _this._clearGizmos();
  89392. }
  89393. }
  89394. }
  89395. }
  89396. }
  89397. });
  89398. }
  89399. /**
  89400. * Disposes of the gizmo manager
  89401. */
  89402. GizmoManager.prototype.dispose = function () {
  89403. this.scene.onPointerObservable.remove(this._pointerObserver);
  89404. this._clearGizmos();
  89405. this._gizmoLayer.dispose();
  89406. };
  89407. GizmoManager.prototype._clearGizmos = function () {
  89408. for (var key in this._gizmoSet) {
  89409. if (this._gizmoSet.hasOwnProperty(key)) {
  89410. this._gizmoSet[key].positionGizmo.dispose();
  89411. this._gizmoSet[key].rotationGizmo.dispose();
  89412. delete this._gizmoSet[key];
  89413. }
  89414. }
  89415. };
  89416. return GizmoManager;
  89417. }());
  89418. BABYLON.GizmoManager = GizmoManager;
  89419. })(BABYLON || (BABYLON = {}));
  89420. //# sourceMappingURL=babylon.gizmoManager.js.map
  89421. var BABYLON;
  89422. (function (BABYLON) {
  89423. /**
  89424. * Defines a target to use with MorphTargetManager
  89425. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89426. */
  89427. var MorphTarget = /** @class */ (function () {
  89428. /**
  89429. * Creates a new MorphTarget
  89430. * @param name defines the name of the target
  89431. * @param influence defines the influence to use
  89432. */
  89433. function MorphTarget(
  89434. /** defines the name of the target */
  89435. name, influence, scene) {
  89436. if (influence === void 0) { influence = 0; }
  89437. if (scene === void 0) { scene = null; }
  89438. this.name = name;
  89439. /**
  89440. * Gets or sets the list of animations
  89441. */
  89442. this.animations = new Array();
  89443. this._positions = null;
  89444. this._normals = null;
  89445. this._tangents = null;
  89446. /**
  89447. * Observable raised when the influence changes
  89448. */
  89449. this.onInfluenceChanged = new BABYLON.Observable();
  89450. this._animationPropertiesOverride = null;
  89451. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89452. this.influence = influence;
  89453. }
  89454. Object.defineProperty(MorphTarget.prototype, "influence", {
  89455. /**
  89456. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89457. */
  89458. get: function () {
  89459. return this._influence;
  89460. },
  89461. set: function (influence) {
  89462. if (this._influence === influence) {
  89463. return;
  89464. }
  89465. var previous = this._influence;
  89466. this._influence = influence;
  89467. if (this.onInfluenceChanged.hasObservers) {
  89468. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89469. }
  89470. },
  89471. enumerable: true,
  89472. configurable: true
  89473. });
  89474. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89475. /**
  89476. * Gets or sets the animation properties override
  89477. */
  89478. get: function () {
  89479. if (!this._animationPropertiesOverride && this._scene) {
  89480. return this._scene.animationPropertiesOverride;
  89481. }
  89482. return this._animationPropertiesOverride;
  89483. },
  89484. set: function (value) {
  89485. this._animationPropertiesOverride = value;
  89486. },
  89487. enumerable: true,
  89488. configurable: true
  89489. });
  89490. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89491. /**
  89492. * Gets a boolean defining if the target contains position data
  89493. */
  89494. get: function () {
  89495. return !!this._positions;
  89496. },
  89497. enumerable: true,
  89498. configurable: true
  89499. });
  89500. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89501. /**
  89502. * Gets a boolean defining if the target contains normal data
  89503. */
  89504. get: function () {
  89505. return !!this._normals;
  89506. },
  89507. enumerable: true,
  89508. configurable: true
  89509. });
  89510. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89511. /**
  89512. * Gets a boolean defining if the target contains tangent data
  89513. */
  89514. get: function () {
  89515. return !!this._tangents;
  89516. },
  89517. enumerable: true,
  89518. configurable: true
  89519. });
  89520. /**
  89521. * Affects position data to this target
  89522. * @param data defines the position data to use
  89523. */
  89524. MorphTarget.prototype.setPositions = function (data) {
  89525. this._positions = data;
  89526. };
  89527. /**
  89528. * Gets the position data stored in this target
  89529. * @returns a FloatArray containing the position data (or null if not present)
  89530. */
  89531. MorphTarget.prototype.getPositions = function () {
  89532. return this._positions;
  89533. };
  89534. /**
  89535. * Affects normal data to this target
  89536. * @param data defines the normal data to use
  89537. */
  89538. MorphTarget.prototype.setNormals = function (data) {
  89539. this._normals = data;
  89540. };
  89541. /**
  89542. * Gets the normal data stored in this target
  89543. * @returns a FloatArray containing the normal data (or null if not present)
  89544. */
  89545. MorphTarget.prototype.getNormals = function () {
  89546. return this._normals;
  89547. };
  89548. /**
  89549. * Affects tangent data to this target
  89550. * @param data defines the tangent data to use
  89551. */
  89552. MorphTarget.prototype.setTangents = function (data) {
  89553. this._tangents = data;
  89554. };
  89555. /**
  89556. * Gets the tangent data stored in this target
  89557. * @returns a FloatArray containing the tangent data (or null if not present)
  89558. */
  89559. MorphTarget.prototype.getTangents = function () {
  89560. return this._tangents;
  89561. };
  89562. /**
  89563. * Serializes the current target into a Serialization object
  89564. * @returns the serialized object
  89565. */
  89566. MorphTarget.prototype.serialize = function () {
  89567. var serializationObject = {};
  89568. serializationObject.name = this.name;
  89569. serializationObject.influence = this.influence;
  89570. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89571. if (this.hasNormals) {
  89572. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89573. }
  89574. if (this.hasTangents) {
  89575. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89576. }
  89577. // Animations
  89578. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89579. return serializationObject;
  89580. };
  89581. // Statics
  89582. /**
  89583. * Creates a new target from serialized data
  89584. * @param serializationObject defines the serialized data to use
  89585. * @returns a new MorphTarget
  89586. */
  89587. MorphTarget.Parse = function (serializationObject) {
  89588. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89589. result.setPositions(serializationObject.positions);
  89590. if (serializationObject.normals) {
  89591. result.setNormals(serializationObject.normals);
  89592. }
  89593. if (serializationObject.tangents) {
  89594. result.setTangents(serializationObject.tangents);
  89595. }
  89596. // Animations
  89597. if (serializationObject.animations) {
  89598. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89599. var parsedAnimation = serializationObject.animations[animationIndex];
  89600. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89601. }
  89602. }
  89603. return result;
  89604. };
  89605. /**
  89606. * Creates a MorphTarget from mesh data
  89607. * @param mesh defines the source mesh
  89608. * @param name defines the name to use for the new target
  89609. * @param influence defines the influence to attach to the target
  89610. * @returns a new MorphTarget
  89611. */
  89612. MorphTarget.FromMesh = function (mesh, name, influence) {
  89613. if (!name) {
  89614. name = mesh.name;
  89615. }
  89616. var result = new MorphTarget(name, influence, mesh.getScene());
  89617. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89619. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89620. }
  89621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89622. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89623. }
  89624. return result;
  89625. };
  89626. return MorphTarget;
  89627. }());
  89628. BABYLON.MorphTarget = MorphTarget;
  89629. })(BABYLON || (BABYLON = {}));
  89630. //# sourceMappingURL=babylon.morphTarget.js.map
  89631. var BABYLON;
  89632. (function (BABYLON) {
  89633. /**
  89634. * This class is used to deform meshes using morphing between different targets
  89635. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89636. */
  89637. var MorphTargetManager = /** @class */ (function () {
  89638. /**
  89639. * Creates a new MorphTargetManager
  89640. * @param scene defines the current scene
  89641. */
  89642. function MorphTargetManager(scene) {
  89643. if (scene === void 0) { scene = null; }
  89644. this._targets = new Array();
  89645. this._targetObservable = new Array();
  89646. this._activeTargets = new BABYLON.SmartArray(16);
  89647. this._supportsNormals = false;
  89648. this._supportsTangents = false;
  89649. this._vertexCount = 0;
  89650. this._uniqueId = 0;
  89651. this._tempInfluences = new Array();
  89652. if (!scene) {
  89653. scene = BABYLON.Engine.LastCreatedScene;
  89654. }
  89655. this._scene = scene;
  89656. if (this._scene) {
  89657. this._scene.morphTargetManagers.push(this);
  89658. this._uniqueId = this._scene.getUniqueId();
  89659. }
  89660. }
  89661. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89662. /**
  89663. * Gets the unique ID of this manager
  89664. */
  89665. get: function () {
  89666. return this._uniqueId;
  89667. },
  89668. enumerable: true,
  89669. configurable: true
  89670. });
  89671. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89672. /**
  89673. * Gets the number of vertices handled by this manager
  89674. */
  89675. get: function () {
  89676. return this._vertexCount;
  89677. },
  89678. enumerable: true,
  89679. configurable: true
  89680. });
  89681. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89682. /**
  89683. * Gets a boolean indicating if this manager supports morphing of normals
  89684. */
  89685. get: function () {
  89686. return this._supportsNormals;
  89687. },
  89688. enumerable: true,
  89689. configurable: true
  89690. });
  89691. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89692. /**
  89693. * Gets a boolean indicating if this manager supports morphing of tangents
  89694. */
  89695. get: function () {
  89696. return this._supportsTangents;
  89697. },
  89698. enumerable: true,
  89699. configurable: true
  89700. });
  89701. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89702. /**
  89703. * Gets the number of targets stored in this manager
  89704. */
  89705. get: function () {
  89706. return this._targets.length;
  89707. },
  89708. enumerable: true,
  89709. configurable: true
  89710. });
  89711. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89712. /**
  89713. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89714. */
  89715. get: function () {
  89716. return this._activeTargets.length;
  89717. },
  89718. enumerable: true,
  89719. configurable: true
  89720. });
  89721. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89722. /**
  89723. * Gets the list of influences (one per target)
  89724. */
  89725. get: function () {
  89726. return this._influences;
  89727. },
  89728. enumerable: true,
  89729. configurable: true
  89730. });
  89731. /**
  89732. * Gets the active target at specified index. An active target is a target with an influence > 0
  89733. * @param index defines the index to check
  89734. * @returns the requested target
  89735. */
  89736. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89737. return this._activeTargets.data[index];
  89738. };
  89739. /**
  89740. * Gets the target at specified index
  89741. * @param index defines the index to check
  89742. * @returns the requested target
  89743. */
  89744. MorphTargetManager.prototype.getTarget = function (index) {
  89745. return this._targets[index];
  89746. };
  89747. /**
  89748. * Add a new target to this manager
  89749. * @param target defines the target to add
  89750. */
  89751. MorphTargetManager.prototype.addTarget = function (target) {
  89752. var _this = this;
  89753. this._targets.push(target);
  89754. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89755. _this._syncActiveTargets(needUpdate);
  89756. }));
  89757. this._syncActiveTargets(true);
  89758. };
  89759. /**
  89760. * Removes a target from the manager
  89761. * @param target defines the target to remove
  89762. */
  89763. MorphTargetManager.prototype.removeTarget = function (target) {
  89764. var index = this._targets.indexOf(target);
  89765. if (index >= 0) {
  89766. this._targets.splice(index, 1);
  89767. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89768. this._syncActiveTargets(true);
  89769. }
  89770. };
  89771. /**
  89772. * Serializes the current manager into a Serialization object
  89773. * @returns the serialized object
  89774. */
  89775. MorphTargetManager.prototype.serialize = function () {
  89776. var serializationObject = {};
  89777. serializationObject.id = this.uniqueId;
  89778. serializationObject.targets = [];
  89779. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89780. var target = _a[_i];
  89781. serializationObject.targets.push(target.serialize());
  89782. }
  89783. return serializationObject;
  89784. };
  89785. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89786. var influenceCount = 0;
  89787. this._activeTargets.reset();
  89788. this._supportsNormals = true;
  89789. this._supportsTangents = true;
  89790. this._vertexCount = 0;
  89791. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89792. var target = _a[_i];
  89793. this._activeTargets.push(target);
  89794. this._tempInfluences[influenceCount++] = target.influence;
  89795. var positions = target.getPositions();
  89796. if (positions) {
  89797. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89798. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89799. var vertexCount = positions.length / 3;
  89800. if (this._vertexCount === 0) {
  89801. this._vertexCount = vertexCount;
  89802. }
  89803. else if (this._vertexCount !== vertexCount) {
  89804. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89805. return;
  89806. }
  89807. }
  89808. }
  89809. if (!this._influences || this._influences.length !== influenceCount) {
  89810. this._influences = new Float32Array(influenceCount);
  89811. }
  89812. for (var index = 0; index < influenceCount; index++) {
  89813. this._influences[index] = this._tempInfluences[index];
  89814. }
  89815. if (needUpdate) {
  89816. this.synchronize();
  89817. }
  89818. };
  89819. /**
  89820. * Syncrhonize the targets with all the meshes using this morph target manager
  89821. */
  89822. MorphTargetManager.prototype.synchronize = function () {
  89823. if (!this._scene) {
  89824. return;
  89825. }
  89826. // Flag meshes as dirty to resync with the active targets
  89827. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89828. var mesh = _a[_i];
  89829. if (mesh.morphTargetManager === this) {
  89830. mesh._syncGeometryWithMorphTargetManager();
  89831. }
  89832. }
  89833. };
  89834. // Statics
  89835. /**
  89836. * Creates a new MorphTargetManager from serialized data
  89837. * @param serializationObject defines the serialized data
  89838. * @param scene defines the hosting scene
  89839. * @returns the new MorphTargetManager
  89840. */
  89841. MorphTargetManager.Parse = function (serializationObject, scene) {
  89842. var result = new MorphTargetManager(scene);
  89843. result._uniqueId = serializationObject.id;
  89844. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89845. var targetData = _a[_i];
  89846. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89847. }
  89848. return result;
  89849. };
  89850. return MorphTargetManager;
  89851. }());
  89852. BABYLON.MorphTargetManager = MorphTargetManager;
  89853. })(BABYLON || (BABYLON = {}));
  89854. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89855. var BABYLON;
  89856. (function (BABYLON) {
  89857. var Octree = /** @class */ (function () {
  89858. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89859. if (maxDepth === void 0) { maxDepth = 2; }
  89860. this.maxDepth = maxDepth;
  89861. this.dynamicContent = new Array();
  89862. this._maxBlockCapacity = maxBlockCapacity || 64;
  89863. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89864. this._creationFunc = creationFunc;
  89865. }
  89866. // Methods
  89867. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89868. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89869. };
  89870. Octree.prototype.addMesh = function (entry) {
  89871. for (var index = 0; index < this.blocks.length; index++) {
  89872. var block = this.blocks[index];
  89873. block.addEntry(entry);
  89874. }
  89875. };
  89876. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89877. this._selectionContent.reset();
  89878. for (var index = 0; index < this.blocks.length; index++) {
  89879. var block = this.blocks[index];
  89880. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89881. }
  89882. if (allowDuplicate) {
  89883. this._selectionContent.concat(this.dynamicContent);
  89884. }
  89885. else {
  89886. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89887. }
  89888. return this._selectionContent;
  89889. };
  89890. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89891. this._selectionContent.reset();
  89892. for (var index = 0; index < this.blocks.length; index++) {
  89893. var block = this.blocks[index];
  89894. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89895. }
  89896. if (allowDuplicate) {
  89897. this._selectionContent.concat(this.dynamicContent);
  89898. }
  89899. else {
  89900. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89901. }
  89902. return this._selectionContent;
  89903. };
  89904. Octree.prototype.intersectsRay = function (ray) {
  89905. this._selectionContent.reset();
  89906. for (var index = 0; index < this.blocks.length; index++) {
  89907. var block = this.blocks[index];
  89908. block.intersectsRay(ray, this._selectionContent);
  89909. }
  89910. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89911. return this._selectionContent;
  89912. };
  89913. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89914. target.blocks = new Array();
  89915. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89916. // Segmenting space
  89917. for (var x = 0; x < 2; x++) {
  89918. for (var y = 0; y < 2; y++) {
  89919. for (var z = 0; z < 2; z++) {
  89920. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89921. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89922. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89923. block.addEntries(entries);
  89924. target.blocks.push(block);
  89925. }
  89926. }
  89927. }
  89928. };
  89929. Octree.CreationFuncForMeshes = function (entry, block) {
  89930. var boundingInfo = entry.getBoundingInfo();
  89931. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89932. block.entries.push(entry);
  89933. }
  89934. };
  89935. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89936. var boundingInfo = entry.getBoundingInfo();
  89937. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89938. block.entries.push(entry);
  89939. }
  89940. };
  89941. return Octree;
  89942. }());
  89943. BABYLON.Octree = Octree;
  89944. })(BABYLON || (BABYLON = {}));
  89945. //# sourceMappingURL=babylon.octree.js.map
  89946. var BABYLON;
  89947. (function (BABYLON) {
  89948. var OctreeBlock = /** @class */ (function () {
  89949. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89950. this.entries = new Array();
  89951. this._boundingVectors = new Array();
  89952. this._capacity = capacity;
  89953. this._depth = depth;
  89954. this._maxDepth = maxDepth;
  89955. this._creationFunc = creationFunc;
  89956. this._minPoint = minPoint;
  89957. this._maxPoint = maxPoint;
  89958. this._boundingVectors.push(minPoint.clone());
  89959. this._boundingVectors.push(maxPoint.clone());
  89960. this._boundingVectors.push(minPoint.clone());
  89961. this._boundingVectors[2].x = maxPoint.x;
  89962. this._boundingVectors.push(minPoint.clone());
  89963. this._boundingVectors[3].y = maxPoint.y;
  89964. this._boundingVectors.push(minPoint.clone());
  89965. this._boundingVectors[4].z = maxPoint.z;
  89966. this._boundingVectors.push(maxPoint.clone());
  89967. this._boundingVectors[5].z = minPoint.z;
  89968. this._boundingVectors.push(maxPoint.clone());
  89969. this._boundingVectors[6].x = minPoint.x;
  89970. this._boundingVectors.push(maxPoint.clone());
  89971. this._boundingVectors[7].y = minPoint.y;
  89972. }
  89973. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89974. // Property
  89975. get: function () {
  89976. return this._capacity;
  89977. },
  89978. enumerable: true,
  89979. configurable: true
  89980. });
  89981. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89982. get: function () {
  89983. return this._minPoint;
  89984. },
  89985. enumerable: true,
  89986. configurable: true
  89987. });
  89988. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89989. get: function () {
  89990. return this._maxPoint;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. // Methods
  89996. OctreeBlock.prototype.addEntry = function (entry) {
  89997. if (this.blocks) {
  89998. for (var index = 0; index < this.blocks.length; index++) {
  89999. var block = this.blocks[index];
  90000. block.addEntry(entry);
  90001. }
  90002. return;
  90003. }
  90004. this._creationFunc(entry, this);
  90005. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90006. this.createInnerBlocks();
  90007. }
  90008. };
  90009. OctreeBlock.prototype.addEntries = function (entries) {
  90010. for (var index = 0; index < entries.length; index++) {
  90011. var mesh = entries[index];
  90012. this.addEntry(mesh);
  90013. }
  90014. };
  90015. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90016. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90017. if (this.blocks) {
  90018. for (var index = 0; index < this.blocks.length; index++) {
  90019. var block = this.blocks[index];
  90020. block.select(frustumPlanes, selection, allowDuplicate);
  90021. }
  90022. return;
  90023. }
  90024. if (allowDuplicate) {
  90025. selection.concat(this.entries);
  90026. }
  90027. else {
  90028. selection.concatWithNoDuplicate(this.entries);
  90029. }
  90030. }
  90031. };
  90032. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90033. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90034. if (this.blocks) {
  90035. for (var index = 0; index < this.blocks.length; index++) {
  90036. var block = this.blocks[index];
  90037. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90038. }
  90039. return;
  90040. }
  90041. if (allowDuplicate) {
  90042. selection.concat(this.entries);
  90043. }
  90044. else {
  90045. selection.concatWithNoDuplicate(this.entries);
  90046. }
  90047. }
  90048. };
  90049. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90050. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90051. if (this.blocks) {
  90052. for (var index = 0; index < this.blocks.length; index++) {
  90053. var block = this.blocks[index];
  90054. block.intersectsRay(ray, selection);
  90055. }
  90056. return;
  90057. }
  90058. selection.concatWithNoDuplicate(this.entries);
  90059. }
  90060. };
  90061. OctreeBlock.prototype.createInnerBlocks = function () {
  90062. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90063. };
  90064. return OctreeBlock;
  90065. }());
  90066. BABYLON.OctreeBlock = OctreeBlock;
  90067. })(BABYLON || (BABYLON = {}));
  90068. //# sourceMappingURL=babylon.octreeBlock.js.map
  90069. var BABYLON;
  90070. (function (BABYLON) {
  90071. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90072. __extends(VRDistortionCorrectionPostProcess, _super);
  90073. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90074. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90075. 'LensCenter',
  90076. 'Scale',
  90077. 'ScaleIn',
  90078. 'HmdWarpParam'
  90079. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90080. _this._isRightEye = isRightEye;
  90081. _this._distortionFactors = vrMetrics.distortionK;
  90082. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90083. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90084. _this.adaptScaleToCurrentViewport = true;
  90085. _this.onSizeChangedObservable.add(function () {
  90086. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90087. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90088. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90089. });
  90090. _this.onApplyObservable.add(function (effect) {
  90091. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90092. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90093. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90094. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90095. });
  90096. return _this;
  90097. }
  90098. return VRDistortionCorrectionPostProcess;
  90099. }(BABYLON.PostProcess));
  90100. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90101. })(BABYLON || (BABYLON = {}));
  90102. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90103. var BABYLON;
  90104. (function (BABYLON) {
  90105. /**
  90106. * Postprocess used to generate anaglyphic rendering
  90107. */
  90108. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90109. __extends(AnaglyphPostProcess, _super);
  90110. /**
  90111. * Creates a new AnaglyphPostProcess
  90112. * @param name defines postprocess name
  90113. * @param options defines creation options or target ratio scale
  90114. * @param rigCameras defines cameras using this postprocess
  90115. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90116. * @param engine defines hosting engine
  90117. * @param reusable defines if the postprocess will be reused multiple times per frame
  90118. */
  90119. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90120. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90121. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90122. _this.onApplyObservable.add(function (effect) {
  90123. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90124. });
  90125. return _this;
  90126. }
  90127. return AnaglyphPostProcess;
  90128. }(BABYLON.PostProcess));
  90129. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90130. })(BABYLON || (BABYLON = {}));
  90131. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90132. var BABYLON;
  90133. (function (BABYLON) {
  90134. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90135. __extends(StereoscopicInterlacePostProcess, _super);
  90136. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90137. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90138. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90139. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90140. _this.onSizeChangedObservable.add(function () {
  90141. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90142. });
  90143. _this.onApplyObservable.add(function (effect) {
  90144. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90145. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90146. });
  90147. return _this;
  90148. }
  90149. return StereoscopicInterlacePostProcess;
  90150. }(BABYLON.PostProcess));
  90151. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90152. })(BABYLON || (BABYLON = {}));
  90153. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90154. var BABYLON;
  90155. (function (BABYLON) {
  90156. /**
  90157. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90158. * Screen rotation is taken into account.
  90159. */
  90160. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90161. function FreeCameraDeviceOrientationInput() {
  90162. var _this = this;
  90163. this._screenOrientationAngle = 0;
  90164. this._screenQuaternion = new BABYLON.Quaternion();
  90165. this._alpha = 0;
  90166. this._beta = 0;
  90167. this._gamma = 0;
  90168. this._orientationChanged = function () {
  90169. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90170. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90171. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90172. };
  90173. this._deviceOrientation = function (evt) {
  90174. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90175. _this._beta = evt.beta !== null ? evt.beta : 0;
  90176. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90177. };
  90178. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90179. this._orientationChanged();
  90180. }
  90181. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90182. get: function () {
  90183. return this._camera;
  90184. },
  90185. set: function (camera) {
  90186. this._camera = camera;
  90187. if (this._camera != null && !this._camera.rotationQuaternion) {
  90188. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90189. }
  90190. },
  90191. enumerable: true,
  90192. configurable: true
  90193. });
  90194. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90195. window.addEventListener("orientationchange", this._orientationChanged);
  90196. window.addEventListener("deviceorientation", this._deviceOrientation);
  90197. //In certain cases, the attach control is called AFTER orientation was changed,
  90198. //So this is needed.
  90199. this._orientationChanged();
  90200. };
  90201. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90202. window.removeEventListener("orientationchange", this._orientationChanged);
  90203. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90204. };
  90205. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90206. //if no device orientation provided, don't update the rotation.
  90207. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90208. if (!this._alpha)
  90209. return;
  90210. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90211. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90212. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90213. //Mirror on XY Plane
  90214. this._camera.rotationQuaternion.z *= -1;
  90215. this._camera.rotationQuaternion.w *= -1;
  90216. };
  90217. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90218. return "FreeCameraDeviceOrientationInput";
  90219. };
  90220. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90221. return "deviceOrientation";
  90222. };
  90223. return FreeCameraDeviceOrientationInput;
  90224. }());
  90225. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90226. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90227. })(BABYLON || (BABYLON = {}));
  90228. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90229. var BABYLON;
  90230. (function (BABYLON) {
  90231. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90232. function ArcRotateCameraVRDeviceOrientationInput() {
  90233. this.alphaCorrection = 1;
  90234. this.betaCorrection = 1;
  90235. this.gammaCorrection = 1;
  90236. this._alpha = 0;
  90237. this._gamma = 0;
  90238. this._dirty = false;
  90239. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90240. }
  90241. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90242. this.camera.attachControl(element, noPreventDefault);
  90243. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90244. };
  90245. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90246. if (evt.alpha !== null) {
  90247. this._alpha = +evt.alpha | 0;
  90248. }
  90249. if (evt.gamma !== null) {
  90250. this._gamma = +evt.gamma | 0;
  90251. }
  90252. this._dirty = true;
  90253. };
  90254. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90255. if (this._dirty) {
  90256. this._dirty = false;
  90257. if (this._gamma < 0) {
  90258. this._gamma = 180 + this._gamma;
  90259. }
  90260. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90261. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90262. }
  90263. };
  90264. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90265. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90266. };
  90267. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90268. return "ArcRotateCameraVRDeviceOrientationInput";
  90269. };
  90270. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90271. return "VRDeviceOrientation";
  90272. };
  90273. return ArcRotateCameraVRDeviceOrientationInput;
  90274. }());
  90275. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90276. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90277. })(BABYLON || (BABYLON = {}));
  90278. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90279. var BABYLON;
  90280. (function (BABYLON) {
  90281. var VRCameraMetrics = /** @class */ (function () {
  90282. function VRCameraMetrics() {
  90283. this.compensateDistortion = true;
  90284. }
  90285. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90286. get: function () {
  90287. return this.hResolution / (2 * this.vResolution);
  90288. },
  90289. enumerable: true,
  90290. configurable: true
  90291. });
  90292. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90293. get: function () {
  90294. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90295. },
  90296. enumerable: true,
  90297. configurable: true
  90298. });
  90299. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90300. get: function () {
  90301. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90302. var h = (4 * meters) / this.hScreenSize;
  90303. return BABYLON.Matrix.Translation(h, 0, 0);
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90309. get: function () {
  90310. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90311. var h = (4 * meters) / this.hScreenSize;
  90312. return BABYLON.Matrix.Translation(-h, 0, 0);
  90313. },
  90314. enumerable: true,
  90315. configurable: true
  90316. });
  90317. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90318. get: function () {
  90319. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90320. },
  90321. enumerable: true,
  90322. configurable: true
  90323. });
  90324. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90325. get: function () {
  90326. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90327. },
  90328. enumerable: true,
  90329. configurable: true
  90330. });
  90331. VRCameraMetrics.GetDefault = function () {
  90332. var result = new VRCameraMetrics();
  90333. result.hResolution = 1280;
  90334. result.vResolution = 800;
  90335. result.hScreenSize = 0.149759993;
  90336. result.vScreenSize = 0.0935999975;
  90337. result.vScreenCenter = 0.0467999987;
  90338. result.eyeToScreenDistance = 0.0410000011;
  90339. result.lensSeparationDistance = 0.0635000020;
  90340. result.interpupillaryDistance = 0.0640000030;
  90341. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90342. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90343. result.postProcessScaleFactor = 1.714605507808412;
  90344. result.lensCenterOffset = 0.151976421;
  90345. return result;
  90346. };
  90347. return VRCameraMetrics;
  90348. }());
  90349. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90350. })(BABYLON || (BABYLON = {}));
  90351. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90352. var BABYLON;
  90353. (function (BABYLON) {
  90354. /**
  90355. * This represents a WebVR camera.
  90356. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90357. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90358. */
  90359. var WebVRFreeCamera = /** @class */ (function (_super) {
  90360. __extends(WebVRFreeCamera, _super);
  90361. /**
  90362. * Instantiates a WebVRFreeCamera.
  90363. * @param name The name of the WebVRFreeCamera
  90364. * @param position The starting anchor position for the camera
  90365. * @param scene The scene the camera belongs to
  90366. * @param webVROptions a set of customizable options for the webVRCamera
  90367. */
  90368. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90369. if (webVROptions === void 0) { webVROptions = {}; }
  90370. var _this = _super.call(this, name, position, scene) || this;
  90371. _this.webVROptions = webVROptions;
  90372. /**
  90373. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90374. */
  90375. _this._vrDevice = null;
  90376. /**
  90377. * The rawPose of the vrDevice.
  90378. */
  90379. _this.rawPose = null;
  90380. _this._specsVersion = "1.1";
  90381. _this._attached = false;
  90382. _this._descendants = [];
  90383. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90384. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90385. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90386. _this._standingMatrix = null;
  90387. /**
  90388. * Represents device position in babylon space.
  90389. */
  90390. _this.devicePosition = BABYLON.Vector3.Zero();
  90391. /**
  90392. * Represents device rotation in babylon space.
  90393. */
  90394. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90395. /**
  90396. * The scale of the device to be used when translating from device space to babylon space.
  90397. */
  90398. _this.deviceScaleFactor = 1;
  90399. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90400. _this._worldToDevice = BABYLON.Matrix.Identity();
  90401. /**
  90402. * References to the webVR controllers for the vrDevice.
  90403. */
  90404. _this.controllers = [];
  90405. /**
  90406. * Emits an event when a controller is attached.
  90407. */
  90408. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90409. /**
  90410. * Emits an event when a controller's mesh has been loaded;
  90411. */
  90412. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90413. /**
  90414. * If the rig cameras be used as parent instead of this camera.
  90415. */
  90416. _this.rigParenting = true;
  90417. _this._defaultHeight = undefined;
  90418. _this._workingVector = BABYLON.Vector3.Zero();
  90419. _this._oneVector = BABYLON.Vector3.One();
  90420. _this._workingMatrix = BABYLON.Matrix.Identity();
  90421. _this._cache.position = BABYLON.Vector3.Zero();
  90422. if (webVROptions.defaultHeight) {
  90423. _this._defaultHeight = webVROptions.defaultHeight;
  90424. _this.position.y = _this._defaultHeight;
  90425. }
  90426. _this.minZ = 0.1;
  90427. //legacy support - the compensation boolean was removed.
  90428. if (arguments.length === 5) {
  90429. _this.webVROptions = arguments[4];
  90430. }
  90431. // default webVR options
  90432. if (_this.webVROptions.trackPosition == undefined) {
  90433. _this.webVROptions.trackPosition = true;
  90434. }
  90435. if (_this.webVROptions.controllerMeshes == undefined) {
  90436. _this.webVROptions.controllerMeshes = true;
  90437. }
  90438. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90439. _this.webVROptions.defaultLightingOnControllers = true;
  90440. }
  90441. _this.rotationQuaternion = new BABYLON.Quaternion();
  90442. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90443. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90444. }
  90445. //enable VR
  90446. var engine = _this.getEngine();
  90447. _this._onVREnabled = function (success) { if (success) {
  90448. _this.initControllers();
  90449. } };
  90450. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90451. engine.initWebVR().add(function (event) {
  90452. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90453. return;
  90454. }
  90455. _this._vrDevice = event.vrDisplay;
  90456. //reset the rig parameters.
  90457. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90458. if (_this._attached) {
  90459. _this.getEngine().enableVR();
  90460. }
  90461. });
  90462. if (typeof (VRFrameData) !== "undefined")
  90463. _this._frameData = new VRFrameData();
  90464. /**
  90465. * The idea behind the following lines:
  90466. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90467. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90468. * the second will not show it correctly.
  90469. *
  90470. * To solve this - each object that has the camera as parent will be added to a protected array.
  90471. * When the rig camera renders, it will take this array and set all of those to be its children.
  90472. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90473. * Amazing!
  90474. */
  90475. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90476. if (camera.parent === _this && _this.rigParenting) {
  90477. _this._descendants = _this.getDescendants(true, function (n) {
  90478. // don't take the cameras or the controllers!
  90479. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90480. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90481. return !isController && !isRigCamera;
  90482. });
  90483. _this._descendants.forEach(function (node) {
  90484. node.parent = camera;
  90485. });
  90486. }
  90487. });
  90488. scene.onAfterCameraRenderObservable.add(function (camera) {
  90489. if (camera.parent === _this && _this.rigParenting) {
  90490. _this._descendants.forEach(function (node) {
  90491. node.parent = _this;
  90492. });
  90493. }
  90494. });
  90495. return _this;
  90496. }
  90497. /**
  90498. * Gets the device distance from the ground in meters.
  90499. * @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.
  90500. */
  90501. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90502. if (this._standingMatrix) {
  90503. // Add standing matrix offset to get real offset from ground in room
  90504. this._standingMatrix.getTranslationToRef(this._workingVector);
  90505. return this._deviceRoomPosition.y + this._workingVector.y;
  90506. }
  90507. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90508. return this._defaultHeight || 0;
  90509. };
  90510. /**
  90511. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90512. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90513. */
  90514. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90515. var _this = this;
  90516. if (callback === void 0) { callback = function (bool) { }; }
  90517. // Use standing matrix if available
  90518. this.getEngine().initWebVRAsync().then(function (result) {
  90519. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90520. callback(false);
  90521. }
  90522. else {
  90523. _this._standingMatrix = new BABYLON.Matrix();
  90524. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90525. if (!_this.getScene().useRightHandedSystem) {
  90526. [2, 6, 8, 9, 14].forEach(function (num) {
  90527. if (_this._standingMatrix) {
  90528. _this._standingMatrix.m[num] *= -1;
  90529. }
  90530. });
  90531. }
  90532. callback(true);
  90533. }
  90534. });
  90535. };
  90536. /**
  90537. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90538. * @returns A promise with a boolean set to if the standing matrix is supported.
  90539. */
  90540. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90541. var _this = this;
  90542. return new Promise(function (res, rej) {
  90543. _this.useStandingMatrix(function (supported) {
  90544. res(supported);
  90545. });
  90546. });
  90547. };
  90548. /**
  90549. * Disposes the camera
  90550. */
  90551. WebVRFreeCamera.prototype.dispose = function () {
  90552. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90553. _super.prototype.dispose.call(this);
  90554. };
  90555. /**
  90556. * Gets a vrController by name.
  90557. * @param name The name of the controller to retreive
  90558. * @returns the controller matching the name specified or null if not found
  90559. */
  90560. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90561. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90562. var gp = _a[_i];
  90563. if (gp.hand === name) {
  90564. return gp;
  90565. }
  90566. }
  90567. return null;
  90568. };
  90569. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90570. /**
  90571. * The controller corrisponding to the users left hand.
  90572. */
  90573. get: function () {
  90574. if (!this._leftController) {
  90575. this._leftController = this.getControllerByName("left");
  90576. }
  90577. return this._leftController;
  90578. },
  90579. enumerable: true,
  90580. configurable: true
  90581. });
  90582. ;
  90583. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90584. /**
  90585. * The controller corrisponding to the users right hand.
  90586. */
  90587. get: function () {
  90588. if (!this._rightController) {
  90589. this._rightController = this.getControllerByName("right");
  90590. }
  90591. return this._rightController;
  90592. },
  90593. enumerable: true,
  90594. configurable: true
  90595. });
  90596. ;
  90597. /**
  90598. * Casts a ray forward from the vrCamera's gaze.
  90599. * @param length Length of the ray (default: 100)
  90600. * @returns the ray corrisponding to the gaze
  90601. */
  90602. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90603. if (length === void 0) { length = 100; }
  90604. if (this.leftCamera) {
  90605. // Use left eye to avoid computation to compute center on every call
  90606. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90607. }
  90608. else {
  90609. return _super.prototype.getForwardRay.call(this, length);
  90610. }
  90611. };
  90612. /**
  90613. * Updates the camera based on device's frame data
  90614. */
  90615. WebVRFreeCamera.prototype._checkInputs = function () {
  90616. if (this._vrDevice && this._vrDevice.isPresenting) {
  90617. this._vrDevice.getFrameData(this._frameData);
  90618. this.updateFromDevice(this._frameData.pose);
  90619. }
  90620. _super.prototype._checkInputs.call(this);
  90621. };
  90622. /**
  90623. * Updates the poseControlled values based on the input device pose.
  90624. * @param poseData Pose coming from the device
  90625. */
  90626. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90627. if (poseData && poseData.orientation) {
  90628. this.rawPose = poseData;
  90629. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90630. if (this.getScene().useRightHandedSystem) {
  90631. this._deviceRoomRotationQuaternion.z *= -1;
  90632. this._deviceRoomRotationQuaternion.w *= -1;
  90633. }
  90634. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90635. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90636. if (this.getScene().useRightHandedSystem) {
  90637. this._deviceRoomPosition.z *= -1;
  90638. }
  90639. }
  90640. }
  90641. };
  90642. /**
  90643. * WebVR's attach control will start broadcasting frames to the device.
  90644. * Note that in certain browsers (chrome for example) this function must be called
  90645. * within a user-interaction callback. Example:
  90646. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90647. *
  90648. * @param element html element to attach the vrDevice to
  90649. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90650. */
  90651. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90652. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90653. this._attached = true;
  90654. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90655. if (this._vrDevice) {
  90656. this.getEngine().enableVR();
  90657. }
  90658. };
  90659. /**
  90660. * Detaches the camera from the html element and disables VR
  90661. *
  90662. * @param element html element to detach from
  90663. */
  90664. WebVRFreeCamera.prototype.detachControl = function (element) {
  90665. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90666. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90667. _super.prototype.detachControl.call(this, element);
  90668. this._attached = false;
  90669. this.getEngine().disableVR();
  90670. };
  90671. /**
  90672. * @returns the name of this class
  90673. */
  90674. WebVRFreeCamera.prototype.getClassName = function () {
  90675. return "WebVRFreeCamera";
  90676. };
  90677. /**
  90678. * Calls resetPose on the vrDisplay
  90679. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90680. */
  90681. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90682. //uses the vrDisplay's "resetPose()".
  90683. //pitch and roll won't be affected.
  90684. this._vrDevice.resetPose();
  90685. };
  90686. /**
  90687. * Updates the rig cameras (left and right eye)
  90688. */
  90689. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90690. var camLeft = this._rigCameras[0];
  90691. var camRight = this._rigCameras[1];
  90692. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90693. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90694. camLeft.position.copyFrom(this._deviceRoomPosition);
  90695. camRight.position.copyFrom(this._deviceRoomPosition);
  90696. };
  90697. /**
  90698. * Updates the cached values of the camera
  90699. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90700. */
  90701. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90702. var _this = this;
  90703. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90704. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90705. if (!this.updateCacheCalled) {
  90706. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90707. this.updateCacheCalled = true;
  90708. this.update();
  90709. }
  90710. // Set working vector to the device position in room space rotated by the new rotation
  90711. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90712. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90713. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90714. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90715. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90716. // Add translation from anchor position
  90717. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90718. this._workingVector.addInPlace(this.position);
  90719. this._workingVector.subtractInPlace(this._cache.position);
  90720. this._deviceToWorld.setTranslation(this._workingVector);
  90721. // Set an inverted matrix to be used when updating the camera
  90722. this._deviceToWorld.invertToRef(this._worldToDevice);
  90723. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90724. this.controllers.forEach(function (controller) {
  90725. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90726. controller.update();
  90727. });
  90728. }
  90729. if (!ignoreParentClass) {
  90730. _super.prototype._updateCache.call(this);
  90731. }
  90732. this.updateCacheCalled = false;
  90733. };
  90734. /**
  90735. * Updates the current device position and rotation in the babylon world
  90736. */
  90737. WebVRFreeCamera.prototype.update = function () {
  90738. // Get current device position in babylon world
  90739. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90740. // Get current device rotation in babylon world
  90741. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90742. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90743. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90744. _super.prototype.update.call(this);
  90745. };
  90746. /**
  90747. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90748. * @returns an identity matrix
  90749. */
  90750. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90751. return BABYLON.Matrix.Identity();
  90752. };
  90753. /**
  90754. * This function is called by the two RIG cameras.
  90755. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90756. */
  90757. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90758. var _this = this;
  90759. // Update the parent camera prior to using a child camera to avoid desynchronization
  90760. var parentCamera = this._cameraRigParams["parentCamera"];
  90761. parentCamera._updateCache();
  90762. //WebVR 1.1
  90763. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90764. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90765. if (!this.getScene().useRightHandedSystem) {
  90766. [2, 6, 8, 9, 14].forEach(function (num) {
  90767. _this._webvrViewMatrix.m[num] *= -1;
  90768. });
  90769. }
  90770. // update the camera rotation matrix
  90771. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90772. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90773. // Computing target and final matrix
  90774. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90775. // should the view matrix be updated with scale and position offset?
  90776. if (parentCamera.deviceScaleFactor !== 1) {
  90777. this._webvrViewMatrix.invert();
  90778. // scale the position, if set
  90779. if (parentCamera.deviceScaleFactor) {
  90780. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90781. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90782. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90783. }
  90784. this._webvrViewMatrix.invert();
  90785. }
  90786. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90787. // Compute global position
  90788. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90789. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90790. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90791. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90792. this._markSyncedWithParent();
  90793. return this._webvrViewMatrix;
  90794. };
  90795. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90796. var _this = this;
  90797. var parentCamera = this.parent;
  90798. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90799. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90800. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90801. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90802. //babylon compatible matrix
  90803. if (!this.getScene().useRightHandedSystem) {
  90804. [8, 9, 10, 11].forEach(function (num) {
  90805. _this._projectionMatrix.m[num] *= -1;
  90806. });
  90807. }
  90808. return this._projectionMatrix;
  90809. };
  90810. /**
  90811. * Initializes the controllers and their meshes
  90812. */
  90813. WebVRFreeCamera.prototype.initControllers = function () {
  90814. var _this = this;
  90815. this.controllers = [];
  90816. var manager = this.getScene().gamepadManager;
  90817. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90818. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90819. var webVrController = gamepad;
  90820. if (webVrController.defaultModel) {
  90821. webVrController.defaultModel.setEnabled(false);
  90822. }
  90823. if (webVrController.hand === "right") {
  90824. _this._rightController = null;
  90825. }
  90826. if (webVrController.hand === "left") {
  90827. _this._leftController = null;
  90828. }
  90829. var controllerIndex = _this.controllers.indexOf(webVrController);
  90830. if (controllerIndex !== -1) {
  90831. _this.controllers.splice(controllerIndex, 1);
  90832. }
  90833. }
  90834. });
  90835. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90836. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90837. var webVrController_1 = gamepad;
  90838. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90839. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90840. if (_this.webVROptions.controllerMeshes) {
  90841. if (webVrController_1.defaultModel) {
  90842. webVrController_1.defaultModel.setEnabled(true);
  90843. }
  90844. else {
  90845. // Load the meshes
  90846. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90847. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90848. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90849. if (_this.webVROptions.defaultLightingOnControllers) {
  90850. if (!_this._lightOnControllers) {
  90851. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90852. }
  90853. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90854. var children = mesh.getChildren();
  90855. if (children.length !== 0) {
  90856. children.forEach(function (mesh) {
  90857. light.includedOnlyMeshes.push(mesh);
  90858. activateLightOnSubMeshes_1(mesh, light);
  90859. });
  90860. }
  90861. };
  90862. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90863. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90864. }
  90865. });
  90866. }
  90867. }
  90868. webVrController_1.attachToPoseControlledCamera(_this);
  90869. // since this is async - sanity check. Is the controller already stored?
  90870. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90871. //add to the controllers array
  90872. _this.controllers.push(webVrController_1);
  90873. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90874. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90875. // So we're overriding setting left & right manually to be sure
  90876. var firstViveWandDetected = false;
  90877. for (var i = 0; i < _this.controllers.length; i++) {
  90878. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90879. if (!firstViveWandDetected) {
  90880. firstViveWandDetected = true;
  90881. _this.controllers[i].hand = "left";
  90882. }
  90883. else {
  90884. _this.controllers[i].hand = "right";
  90885. }
  90886. }
  90887. }
  90888. //did we find enough controllers? Great! let the developer know.
  90889. if (_this.controllers.length >= 2) {
  90890. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90891. }
  90892. }
  90893. }
  90894. });
  90895. };
  90896. return WebVRFreeCamera;
  90897. }(BABYLON.FreeCamera));
  90898. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90899. })(BABYLON || (BABYLON = {}));
  90900. //# sourceMappingURL=babylon.webVRCamera.js.map
  90901. var BABYLON;
  90902. (function (BABYLON) {
  90903. // We're mainly based on the logic defined into the FreeCamera code
  90904. /**
  90905. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90906. * being tilted forward or back and left or right.
  90907. */
  90908. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90909. __extends(DeviceOrientationCamera, _super);
  90910. /**
  90911. * Creates a new device orientation camera
  90912. * @param name The name of the camera
  90913. * @param position The start position camera
  90914. * @param scene The scene the camera belongs to
  90915. */
  90916. function DeviceOrientationCamera(name, position, scene) {
  90917. var _this = _super.call(this, name, position, scene) || this;
  90918. _this._quaternionCache = new BABYLON.Quaternion();
  90919. _this.inputs.addDeviceOrientation();
  90920. return _this;
  90921. }
  90922. /**
  90923. * Gets the current instance class name ("DeviceOrientationCamera").
  90924. * This helps avoiding instanceof at run time.
  90925. * @returns the class name
  90926. */
  90927. DeviceOrientationCamera.prototype.getClassName = function () {
  90928. return "DeviceOrientationCamera";
  90929. };
  90930. /**
  90931. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90932. */
  90933. DeviceOrientationCamera.prototype._checkInputs = function () {
  90934. _super.prototype._checkInputs.call(this);
  90935. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90936. if (this._initialQuaternion) {
  90937. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90938. }
  90939. };
  90940. /**
  90941. * Reset the camera to its default orientation on the specified axis only.
  90942. * @param axis The axis to reset
  90943. */
  90944. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90945. var _this = this;
  90946. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90947. //can only work if this camera has a rotation quaternion already.
  90948. if (!this.rotationQuaternion)
  90949. return;
  90950. if (!this._initialQuaternion) {
  90951. this._initialQuaternion = new BABYLON.Quaternion();
  90952. }
  90953. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90954. ['x', 'y', 'z'].forEach(function (axisName) {
  90955. if (!axis[axisName]) {
  90956. _this._initialQuaternion[axisName] = 0;
  90957. }
  90958. else {
  90959. _this._initialQuaternion[axisName] *= -1;
  90960. }
  90961. });
  90962. this._initialQuaternion.normalize();
  90963. //force rotation update
  90964. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90965. };
  90966. return DeviceOrientationCamera;
  90967. }(BABYLON.FreeCamera));
  90968. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90969. })(BABYLON || (BABYLON = {}));
  90970. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90971. var BABYLON;
  90972. (function (BABYLON) {
  90973. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90974. __extends(VRDeviceOrientationFreeCamera, _super);
  90975. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90976. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90977. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90978. var _this = _super.call(this, name, position, scene) || this;
  90979. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90980. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90981. return _this;
  90982. }
  90983. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90984. return "VRDeviceOrientationFreeCamera";
  90985. };
  90986. return VRDeviceOrientationFreeCamera;
  90987. }(BABYLON.DeviceOrientationCamera));
  90988. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90989. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90990. __extends(VRDeviceOrientationGamepadCamera, _super);
  90991. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90992. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90993. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90994. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90995. _this.inputs.addGamepad();
  90996. return _this;
  90997. }
  90998. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90999. return "VRDeviceOrientationGamepadCamera";
  91000. };
  91001. return VRDeviceOrientationGamepadCamera;
  91002. }(VRDeviceOrientationFreeCamera));
  91003. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91004. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91005. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91006. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91007. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91008. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91009. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91010. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91011. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91012. _this.inputs.addVRDeviceOrientation();
  91013. return _this;
  91014. }
  91015. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91016. return "VRDeviceOrientationArcRotateCamera";
  91017. };
  91018. return VRDeviceOrientationArcRotateCamera;
  91019. }(BABYLON.ArcRotateCamera));
  91020. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91021. })(BABYLON || (BABYLON = {}));
  91022. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91023. var BABYLON;
  91024. (function (BABYLON) {
  91025. /**
  91026. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91027. */
  91028. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91029. __extends(AnaglyphFreeCamera, _super);
  91030. /**
  91031. * Creates a new AnaglyphFreeCamera
  91032. * @param name defines camera name
  91033. * @param position defines initial position
  91034. * @param interaxialDistance defines distance between each color axis
  91035. * @param scene defines the hosting scene
  91036. */
  91037. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91038. var _this = _super.call(this, name, position, scene) || this;
  91039. _this.interaxialDistance = interaxialDistance;
  91040. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91041. return _this;
  91042. }
  91043. /**
  91044. * Gets camera class name
  91045. * @returns AnaglyphFreeCamera
  91046. */
  91047. AnaglyphFreeCamera.prototype.getClassName = function () {
  91048. return "AnaglyphFreeCamera";
  91049. };
  91050. return AnaglyphFreeCamera;
  91051. }(BABYLON.FreeCamera));
  91052. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91053. /**
  91054. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91055. */
  91056. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91057. __extends(AnaglyphArcRotateCamera, _super);
  91058. /**
  91059. * Creates a new AnaglyphArcRotateCamera
  91060. * @param name defines camera name
  91061. * @param alpha defines alpha angle (in radians)
  91062. * @param beta defines beta angle (in radians)
  91063. * @param radius defines radius
  91064. * @param target defines camera target
  91065. * @param interaxialDistance defines distance between each color axis
  91066. * @param scene defines the hosting scene
  91067. */
  91068. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91069. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91070. _this.interaxialDistance = interaxialDistance;
  91071. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91072. return _this;
  91073. }
  91074. /**
  91075. * Gets camera class name
  91076. * @returns AnaglyphArcRotateCamera
  91077. */
  91078. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91079. return "AnaglyphArcRotateCamera";
  91080. };
  91081. return AnaglyphArcRotateCamera;
  91082. }(BABYLON.ArcRotateCamera));
  91083. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91084. /**
  91085. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91086. */
  91087. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91088. __extends(AnaglyphGamepadCamera, _super);
  91089. /**
  91090. * Creates a new AnaglyphGamepadCamera
  91091. * @param name defines camera name
  91092. * @param position defines initial position
  91093. * @param interaxialDistance defines distance between each color axis
  91094. * @param scene defines the hosting scene
  91095. */
  91096. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91097. var _this = _super.call(this, name, position, scene) || this;
  91098. _this.interaxialDistance = interaxialDistance;
  91099. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91100. return _this;
  91101. }
  91102. /**
  91103. * Gets camera class name
  91104. * @returns AnaglyphGamepadCamera
  91105. */
  91106. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91107. return "AnaglyphGamepadCamera";
  91108. };
  91109. return AnaglyphGamepadCamera;
  91110. }(BABYLON.GamepadCamera));
  91111. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91112. /**
  91113. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91114. */
  91115. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91116. __extends(AnaglyphUniversalCamera, _super);
  91117. /**
  91118. * Creates a new AnaglyphUniversalCamera
  91119. * @param name defines camera name
  91120. * @param position defines initial position
  91121. * @param interaxialDistance defines distance between each color axis
  91122. * @param scene defines the hosting scene
  91123. */
  91124. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91125. var _this = _super.call(this, name, position, scene) || this;
  91126. _this.interaxialDistance = interaxialDistance;
  91127. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91128. return _this;
  91129. }
  91130. /**
  91131. * Gets camera class name
  91132. * @returns AnaglyphUniversalCamera
  91133. */
  91134. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91135. return "AnaglyphUniversalCamera";
  91136. };
  91137. return AnaglyphUniversalCamera;
  91138. }(BABYLON.UniversalCamera));
  91139. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91140. /**
  91141. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91142. */
  91143. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91144. __extends(StereoscopicFreeCamera, _super);
  91145. /**
  91146. * Creates a new StereoscopicFreeCamera
  91147. * @param name defines camera name
  91148. * @param position defines initial position
  91149. * @param interaxialDistance defines distance between each color axis
  91150. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91151. * @param scene defines the hosting scene
  91152. */
  91153. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91154. var _this = _super.call(this, name, position, scene) || this;
  91155. _this.interaxialDistance = interaxialDistance;
  91156. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91157. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91158. return _this;
  91159. }
  91160. /**
  91161. * Gets camera class name
  91162. * @returns StereoscopicFreeCamera
  91163. */
  91164. StereoscopicFreeCamera.prototype.getClassName = function () {
  91165. return "StereoscopicFreeCamera";
  91166. };
  91167. return StereoscopicFreeCamera;
  91168. }(BABYLON.FreeCamera));
  91169. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91170. /**
  91171. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91172. */
  91173. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91174. __extends(StereoscopicArcRotateCamera, _super);
  91175. /**
  91176. * Creates a new StereoscopicArcRotateCamera
  91177. * @param name defines camera name
  91178. * @param alpha defines alpha angle (in radians)
  91179. * @param beta defines beta angle (in radians)
  91180. * @param radius defines radius
  91181. * @param target defines camera target
  91182. * @param interaxialDistance defines distance between each color axis
  91183. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91184. * @param scene defines the hosting scene
  91185. */
  91186. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91187. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91188. _this.interaxialDistance = interaxialDistance;
  91189. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91190. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91191. return _this;
  91192. }
  91193. /**
  91194. * Gets camera class name
  91195. * @returns StereoscopicArcRotateCamera
  91196. */
  91197. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91198. return "StereoscopicArcRotateCamera";
  91199. };
  91200. return StereoscopicArcRotateCamera;
  91201. }(BABYLON.ArcRotateCamera));
  91202. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91203. /**
  91204. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91205. */
  91206. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91207. __extends(StereoscopicGamepadCamera, _super);
  91208. /**
  91209. * Creates a new StereoscopicGamepadCamera
  91210. * @param name defines camera name
  91211. * @param position defines initial position
  91212. * @param interaxialDistance defines distance between each color axis
  91213. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91214. * @param scene defines the hosting scene
  91215. */
  91216. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91217. var _this = _super.call(this, name, position, scene) || this;
  91218. _this.interaxialDistance = interaxialDistance;
  91219. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91220. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91221. return _this;
  91222. }
  91223. /**
  91224. * Gets camera class name
  91225. * @returns StereoscopicGamepadCamera
  91226. */
  91227. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91228. return "StereoscopicGamepadCamera";
  91229. };
  91230. return StereoscopicGamepadCamera;
  91231. }(BABYLON.GamepadCamera));
  91232. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91233. /**
  91234. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91235. */
  91236. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91237. __extends(StereoscopicUniversalCamera, _super);
  91238. /**
  91239. * Creates a new StereoscopicUniversalCamera
  91240. * @param name defines camera name
  91241. * @param position defines initial position
  91242. * @param interaxialDistance defines distance between each color axis
  91243. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91244. * @param scene defines the hosting scene
  91245. */
  91246. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91247. var _this = _super.call(this, name, position, scene) || this;
  91248. _this.interaxialDistance = interaxialDistance;
  91249. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91250. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91251. return _this;
  91252. }
  91253. /**
  91254. * Gets camera class name
  91255. * @returns StereoscopicUniversalCamera
  91256. */
  91257. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91258. return "StereoscopicUniversalCamera";
  91259. };
  91260. return StereoscopicUniversalCamera;
  91261. }(BABYLON.UniversalCamera));
  91262. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91263. })(BABYLON || (BABYLON = {}));
  91264. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91265. var BABYLON;
  91266. (function (BABYLON) {
  91267. var VRExperienceHelperGazer = /** @class */ (function () {
  91268. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91269. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91270. this.scene = scene;
  91271. this._pointerDownOnMeshAsked = false;
  91272. this._isActionableMesh = false;
  91273. this._teleportationRequestInitiated = false;
  91274. this._teleportationBackRequestInitiated = false;
  91275. this._rotationRightAsked = false;
  91276. this._rotationLeftAsked = false;
  91277. this._dpadPressed = true;
  91278. this._activePointer = false;
  91279. this._id = VRExperienceHelperGazer._idCounter++;
  91280. // Gaze tracker
  91281. if (!gazeTrackerToClone) {
  91282. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91283. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91284. this._gazeTracker.isPickable = false;
  91285. this._gazeTracker.isVisible = false;
  91286. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91287. targetMat.specularColor = BABYLON.Color3.Black();
  91288. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91289. targetMat.backFaceCulling = false;
  91290. this._gazeTracker.material = targetMat;
  91291. }
  91292. else {
  91293. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91294. }
  91295. }
  91296. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91297. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91298. };
  91299. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91300. this._pointerDownOnMeshAsked = true;
  91301. if (this._currentHit) {
  91302. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91303. }
  91304. };
  91305. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91306. if (this._currentHit) {
  91307. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91308. }
  91309. this._pointerDownOnMeshAsked = false;
  91310. };
  91311. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91312. this._activePointer = true;
  91313. };
  91314. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91315. this._activePointer = false;
  91316. };
  91317. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91318. if (distance === void 0) { distance = 100; }
  91319. };
  91320. VRExperienceHelperGazer.prototype.dispose = function () {
  91321. this._interactionsEnabled = false;
  91322. this._teleportationEnabled = false;
  91323. if (this._gazeTracker) {
  91324. this._gazeTracker.dispose();
  91325. }
  91326. };
  91327. VRExperienceHelperGazer._idCounter = 0;
  91328. return VRExperienceHelperGazer;
  91329. }());
  91330. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91331. __extends(VRExperienceHelperControllerGazer, _super);
  91332. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91333. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91334. _this.webVRController = webVRController;
  91335. // Laser pointer
  91336. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91337. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91338. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91339. laserPointerMaterial.alpha = 0.6;
  91340. _this._laserPointer.material = laserPointerMaterial;
  91341. _this._laserPointer.rotation.x = Math.PI / 2;
  91342. _this._laserPointer.position.z = -0.5;
  91343. _this._laserPointer.isVisible = false;
  91344. _this._laserPointer.isPickable = false;
  91345. if (!webVRController.mesh) {
  91346. // Create an empty mesh that is used prior to loading the high quality model
  91347. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91348. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91349. preloadPointerPose.rotation.x = -0.7;
  91350. preloadMesh.addChild(preloadPointerPose);
  91351. webVRController.attachToMesh(preloadMesh);
  91352. }
  91353. _this._setLaserPointerParent(webVRController.mesh);
  91354. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91355. _this._setLaserPointerParent(mesh);
  91356. });
  91357. return _this;
  91358. }
  91359. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91360. return this.webVRController.getForwardRay(length);
  91361. };
  91362. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91363. _super.prototype._activatePointer.call(this);
  91364. this._laserPointer.isVisible = true;
  91365. };
  91366. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91367. _super.prototype._deactivatePointer.call(this);
  91368. this._laserPointer.isVisible = false;
  91369. };
  91370. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91371. this._laserPointer.material.emissiveColor = color;
  91372. };
  91373. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91374. var makeNotPick = function (root) {
  91375. root.name += " laserPointer";
  91376. root.isPickable = false;
  91377. root.getChildMeshes().forEach(function (c) {
  91378. makeNotPick(c);
  91379. });
  91380. };
  91381. makeNotPick(mesh);
  91382. var childMeshes = mesh.getChildMeshes();
  91383. this.webVRController._pointingPoseNode = null;
  91384. for (var i = 0; i < childMeshes.length; i++) {
  91385. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91386. mesh = childMeshes[i];
  91387. this.webVRController._pointingPoseNode = mesh;
  91388. break;
  91389. }
  91390. }
  91391. this._laserPointer.parent = mesh;
  91392. };
  91393. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91394. if (distance === void 0) { distance = 100; }
  91395. this._laserPointer.scaling.y = distance;
  91396. this._laserPointer.position.z = -distance / 2;
  91397. };
  91398. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91399. _super.prototype.dispose.call(this);
  91400. this._laserPointer.dispose();
  91401. if (this._meshAttachedObserver) {
  91402. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91403. }
  91404. };
  91405. return VRExperienceHelperControllerGazer;
  91406. }(VRExperienceHelperGazer));
  91407. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91408. __extends(VRExperienceHelperCameraGazer, _super);
  91409. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91410. var _this = _super.call(this, scene) || this;
  91411. _this.getCamera = getCamera;
  91412. return _this;
  91413. }
  91414. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91415. var camera = this.getCamera();
  91416. if (camera) {
  91417. return camera.getForwardRay(length);
  91418. }
  91419. else {
  91420. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91421. }
  91422. };
  91423. return VRExperienceHelperCameraGazer;
  91424. }(VRExperienceHelperGazer));
  91425. /**
  91426. * Helps to quickly add VR support to an existing scene.
  91427. * See http://doc.babylonjs.com/how_to/webvr_helper
  91428. */
  91429. var VRExperienceHelper = /** @class */ (function () {
  91430. /**
  91431. * Instantiates a VRExperienceHelper.
  91432. * Helps to quickly add VR support to an existing scene.
  91433. * @param scene The scene the VRExperienceHelper belongs to.
  91434. * @param webVROptions Options to modify the vr experience helper's behavior.
  91435. */
  91436. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91437. if (webVROptions === void 0) { webVROptions = {}; }
  91438. var _this = this;
  91439. this.webVROptions = webVROptions;
  91440. // Can the system support WebVR, even if a headset isn't plugged in?
  91441. this._webVRsupported = false;
  91442. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91443. this._webVRready = false;
  91444. // Are we waiting for the requestPresent callback to complete?
  91445. this._webVRrequesting = false;
  91446. // Are we presenting to the headset right now?
  91447. this._webVRpresenting = false;
  91448. // Are we presenting in the fullscreen fallback?
  91449. this._fullscreenVRpresenting = false;
  91450. /**
  91451. * Observable raised when entering VR.
  91452. */
  91453. this.onEnteringVRObservable = new BABYLON.Observable();
  91454. /**
  91455. * Observable raised when exiting VR.
  91456. */
  91457. this.onExitingVRObservable = new BABYLON.Observable();
  91458. /**
  91459. * Observable raised when controller mesh is loaded.
  91460. */
  91461. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91462. this._useCustomVRButton = false;
  91463. this._teleportationRequested = false;
  91464. this._teleportActive = false;
  91465. this._floorMeshesCollection = [];
  91466. this._rotationAllowed = true;
  91467. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91468. this._isDefaultTeleportationTarget = true;
  91469. this._teleportationFillColor = "#444444";
  91470. this._teleportationBorderColor = "#FFFFFF";
  91471. this._rotationAngle = 0;
  91472. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91473. this._padSensibilityUp = 0.65;
  91474. this._padSensibilityDown = 0.35;
  91475. this.leftController = null;
  91476. this.rightController = null;
  91477. /**
  91478. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91479. */
  91480. this.onNewMeshSelected = new BABYLON.Observable();
  91481. /**
  91482. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91483. */
  91484. this.onNewMeshPicked = new BABYLON.Observable();
  91485. /**
  91486. * Observable raised before camera teleportation
  91487. */
  91488. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91489. /**
  91490. * Observable raised after camera teleportation
  91491. */
  91492. this.onAfterCameraTeleport = new BABYLON.Observable();
  91493. /**
  91494. * Observable raised when current selected mesh gets unselected
  91495. */
  91496. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91497. /**
  91498. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91499. */
  91500. this.teleportationEnabled = true;
  91501. this._teleportationInitialized = false;
  91502. this._interactionsEnabled = false;
  91503. this._interactionsRequested = false;
  91504. this._displayGaze = true;
  91505. this._displayLaserPointer = true;
  91506. this._onResize = function () {
  91507. _this.moveButtonToBottomRight();
  91508. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91509. _this.exitVR();
  91510. }
  91511. };
  91512. this._onFullscreenChange = function () {
  91513. if (document.fullscreen !== undefined) {
  91514. _this._fullscreenVRpresenting = document.fullscreen;
  91515. }
  91516. else if (document.mozFullScreen !== undefined) {
  91517. _this._fullscreenVRpresenting = document.mozFullScreen;
  91518. }
  91519. else if (document.webkitIsFullScreen !== undefined) {
  91520. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91521. }
  91522. else if (document.msIsFullScreen !== undefined) {
  91523. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91524. }
  91525. else if (document.msFullscreenElement !== undefined) {
  91526. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91527. }
  91528. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91529. _this.exitVR();
  91530. if (!_this._useCustomVRButton) {
  91531. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91532. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91533. }
  91534. }
  91535. };
  91536. this.beforeRender = function () {
  91537. if (_this.leftController && _this.leftController._activePointer) {
  91538. _this._castRayAndSelectObject(_this.leftController);
  91539. }
  91540. if (_this.rightController && _this.rightController._activePointer) {
  91541. _this._castRayAndSelectObject(_this.rightController);
  91542. }
  91543. if (_this._noControllerIsActive) {
  91544. _this._castRayAndSelectObject(_this._cameraGazer);
  91545. }
  91546. else {
  91547. _this._cameraGazer._gazeTracker.isVisible = false;
  91548. }
  91549. };
  91550. this._onNewGamepadConnected = function (gamepad) {
  91551. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91552. if (gamepad.leftStick) {
  91553. gamepad.onleftstickchanged(function (stickValues) {
  91554. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91555. // Listening to classic/xbox gamepad only if no VR controller is active
  91556. if ((!_this.leftController && !_this.rightController) ||
  91557. ((_this.leftController && !_this.leftController._activePointer) &&
  91558. (_this.rightController && !_this.rightController._activePointer))) {
  91559. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91560. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91561. }
  91562. }
  91563. });
  91564. }
  91565. if (gamepad.rightStick) {
  91566. gamepad.onrightstickchanged(function (stickValues) {
  91567. if (_this._teleportationInitialized) {
  91568. _this._checkRotate(stickValues, _this._cameraGazer);
  91569. }
  91570. });
  91571. }
  91572. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91573. gamepad.onbuttondown(function (buttonPressed) {
  91574. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91575. _this._cameraGazer._selectionPointerDown();
  91576. }
  91577. });
  91578. gamepad.onbuttonup(function (buttonPressed) {
  91579. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91580. _this._cameraGazer._selectionPointerUp();
  91581. }
  91582. });
  91583. }
  91584. }
  91585. else {
  91586. var webVRController = gamepad;
  91587. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91588. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91589. _this.rightController = controller;
  91590. }
  91591. else {
  91592. _this.leftController = controller;
  91593. }
  91594. _this._tryEnableInteractionOnController(controller);
  91595. }
  91596. };
  91597. // 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
  91598. this._tryEnableInteractionOnController = function (controller) {
  91599. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91600. _this._enableInteractionOnController(controller);
  91601. }
  91602. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91603. _this._enableTeleportationOnController(controller);
  91604. }
  91605. };
  91606. this._onNewGamepadDisconnected = function (gamepad) {
  91607. if (gamepad instanceof BABYLON.WebVRController) {
  91608. if (gamepad.hand === "left" && _this.leftController != null) {
  91609. _this.leftController.dispose();
  91610. _this.leftController = null;
  91611. }
  91612. if (gamepad.hand === "right" && _this.rightController != null) {
  91613. _this.rightController.dispose();
  91614. _this.rightController = null;
  91615. }
  91616. }
  91617. };
  91618. this._workingVector = BABYLON.Vector3.Zero();
  91619. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91620. this._workingMatrix = BABYLON.Matrix.Identity();
  91621. this._scene = scene;
  91622. this._canvas = scene.getEngine().getRenderingCanvas();
  91623. // Parse options
  91624. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91625. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91626. }
  91627. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91628. webVROptions.createDeviceOrientationCamera = true;
  91629. }
  91630. if (webVROptions.laserToggle === undefined) {
  91631. webVROptions.laserToggle = true;
  91632. }
  91633. if (webVROptions.defaultHeight === undefined) {
  91634. webVROptions.defaultHeight = 1.7;
  91635. }
  91636. if (webVROptions.useCustomVRButton) {
  91637. this._useCustomVRButton = true;
  91638. if (webVROptions.customVRButton) {
  91639. this._btnVR = webVROptions.customVRButton;
  91640. }
  91641. }
  91642. if (webVROptions.rayLength) {
  91643. this._rayLength = webVROptions.rayLength;
  91644. }
  91645. this._defaultHeight = webVROptions.defaultHeight;
  91646. if (webVROptions.positionScale) {
  91647. this._rayLength *= webVROptions.positionScale;
  91648. this._defaultHeight *= webVROptions.positionScale;
  91649. }
  91650. // Set position
  91651. if (this._scene.activeCamera) {
  91652. this._position = this._scene.activeCamera.position.clone();
  91653. }
  91654. else {
  91655. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91656. }
  91657. // Set non-vr camera
  91658. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91659. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91660. // Copy data from existing camera
  91661. if (this._scene.activeCamera) {
  91662. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91663. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91664. // Set rotation from previous camera
  91665. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91666. var targetCamera = this._scene.activeCamera;
  91667. if (targetCamera.rotationQuaternion) {
  91668. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91669. }
  91670. else {
  91671. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91672. }
  91673. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91674. }
  91675. }
  91676. this._scene.activeCamera = this._deviceOrientationCamera;
  91677. if (this._canvas) {
  91678. this._scene.activeCamera.attachControl(this._canvas);
  91679. }
  91680. }
  91681. else {
  91682. this._existingCamera = this._scene.activeCamera;
  91683. }
  91684. // Create VR cameras
  91685. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91686. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91687. }
  91688. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91689. this._webVRCamera.useStandingMatrix();
  91690. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91691. // Create default button
  91692. if (!this._useCustomVRButton) {
  91693. this._btnVR = document.createElement("BUTTON");
  91694. this._btnVR.className = "babylonVRicon";
  91695. this._btnVR.id = "babylonVRiconbtn";
  91696. this._btnVR.title = "Click to switch to VR";
  91697. 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) }";
  91698. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91699. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91700. // css += ".babylonVRicon.vrdisplaysupported { }";
  91701. // css += ".babylonVRicon.vrdisplayready { }";
  91702. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91703. var style = document.createElement('style');
  91704. style.appendChild(document.createTextNode(css));
  91705. document.getElementsByTagName('head')[0].appendChild(style);
  91706. this.moveButtonToBottomRight();
  91707. }
  91708. // VR button click event
  91709. if (this._btnVR) {
  91710. this._btnVR.addEventListener("click", function () {
  91711. if (!_this.isInVRMode) {
  91712. _this.enterVR();
  91713. }
  91714. else {
  91715. _this.exitVR();
  91716. }
  91717. });
  91718. }
  91719. // Window events
  91720. window.addEventListener("resize", this._onResize);
  91721. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91722. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91723. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91724. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91725. document.onmsfullscreenchange = this._onFullscreenChange;
  91726. // Display vr button when headset is connected
  91727. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91728. this.displayVRButton();
  91729. }
  91730. else {
  91731. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91732. if (e.vrDisplay) {
  91733. _this.displayVRButton();
  91734. }
  91735. });
  91736. }
  91737. // Exiting VR mode using 'ESC' key on desktop
  91738. this._onKeyDown = function (event) {
  91739. if (event.keyCode === 27 && _this.isInVRMode) {
  91740. _this.exitVR();
  91741. }
  91742. };
  91743. document.addEventListener("keydown", this._onKeyDown);
  91744. // Exiting VR mode double tapping the touch screen
  91745. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91746. if (_this.isInVRMode) {
  91747. _this.exitVR();
  91748. if (_this._fullscreenVRpresenting) {
  91749. _this._scene.getEngine().switchFullscreen(true);
  91750. }
  91751. }
  91752. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91753. // Listen for WebVR display changes
  91754. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91755. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91756. this._onVRRequestPresentStart = function () {
  91757. _this._webVRrequesting = true;
  91758. _this.updateButtonVisibility();
  91759. };
  91760. this._onVRRequestPresentComplete = function (success) {
  91761. _this._webVRrequesting = false;
  91762. _this.updateButtonVisibility();
  91763. };
  91764. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91765. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91766. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91767. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91768. scene.onDisposeObservable.add(function () {
  91769. _this.dispose();
  91770. });
  91771. // Gamepad connection events
  91772. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91773. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91774. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91775. this.updateButtonVisibility();
  91776. //create easing functions
  91777. this._circleEase = new BABYLON.CircleEase();
  91778. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91779. if (this.webVROptions.floorMeshes) {
  91780. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91781. }
  91782. }
  91783. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91784. /** Return this.onEnteringVRObservable
  91785. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91786. */
  91787. get: function () {
  91788. return this.onEnteringVRObservable;
  91789. },
  91790. enumerable: true,
  91791. configurable: true
  91792. });
  91793. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91794. /** Return this.onExitingVRObservable
  91795. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91796. */
  91797. get: function () {
  91798. return this.onExitingVRObservable;
  91799. },
  91800. enumerable: true,
  91801. configurable: true
  91802. });
  91803. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91804. /** Return this.onControllerMeshLoadedObservable
  91805. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91806. */
  91807. get: function () {
  91808. return this.onControllerMeshLoadedObservable;
  91809. },
  91810. enumerable: true,
  91811. configurable: true
  91812. });
  91813. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91814. /**
  91815. * The mesh used to display where the user is going to teleport.
  91816. */
  91817. get: function () {
  91818. return this._teleportationTarget;
  91819. },
  91820. /**
  91821. * Sets the mesh to be used to display where the user is going to teleport.
  91822. */
  91823. set: function (value) {
  91824. if (value) {
  91825. value.name = "teleportationTarget";
  91826. this._isDefaultTeleportationTarget = false;
  91827. this._teleportationTarget = value;
  91828. }
  91829. },
  91830. enumerable: true,
  91831. configurable: true
  91832. });
  91833. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91834. /**
  91835. * The mesh used to display where the user is selecting,
  91836. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91837. * See http://doc.babylonjs.com/resources/baking_transformations
  91838. */
  91839. get: function () {
  91840. return this._cameraGazer._gazeTracker;
  91841. },
  91842. set: function (value) {
  91843. if (value) {
  91844. this._cameraGazer._gazeTracker = value;
  91845. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91846. this._cameraGazer._gazeTracker.isPickable = false;
  91847. this._cameraGazer._gazeTracker.isVisible = false;
  91848. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91849. if (this.leftController) {
  91850. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91851. }
  91852. if (this.rightController) {
  91853. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91854. }
  91855. }
  91856. },
  91857. enumerable: true,
  91858. configurable: true
  91859. });
  91860. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91861. /**
  91862. * If the ray of the gaze should be displayed.
  91863. */
  91864. get: function () {
  91865. return this._displayGaze;
  91866. },
  91867. /**
  91868. * Sets if the ray of the gaze should be displayed.
  91869. */
  91870. set: function (value) {
  91871. this._displayGaze = value;
  91872. if (!value) {
  91873. this._cameraGazer._gazeTracker.isVisible = false;
  91874. if (this.leftController) {
  91875. this.leftController._gazeTracker.isVisible = false;
  91876. }
  91877. if (this.rightController) {
  91878. this.rightController._gazeTracker.isVisible = false;
  91879. }
  91880. }
  91881. },
  91882. enumerable: true,
  91883. configurable: true
  91884. });
  91885. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91886. /**
  91887. * If the ray of the LaserPointer should be displayed.
  91888. */
  91889. get: function () {
  91890. return this._displayLaserPointer;
  91891. },
  91892. /**
  91893. * Sets if the ray of the LaserPointer should be displayed.
  91894. */
  91895. set: function (value) {
  91896. this._displayLaserPointer = value;
  91897. if (!value) {
  91898. if (this.rightController) {
  91899. this.rightController._deactivatePointer();
  91900. this.rightController._gazeTracker.isVisible = false;
  91901. }
  91902. if (this.leftController) {
  91903. this.leftController._deactivatePointer();
  91904. this.leftController._gazeTracker.isVisible = false;
  91905. }
  91906. }
  91907. else {
  91908. if (this.rightController) {
  91909. this.rightController._activatePointer();
  91910. }
  91911. if (this.leftController) {
  91912. this.leftController._activatePointer();
  91913. }
  91914. }
  91915. },
  91916. enumerable: true,
  91917. configurable: true
  91918. });
  91919. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91920. /**
  91921. * The deviceOrientationCamera used as the camera when not in VR.
  91922. */
  91923. get: function () {
  91924. return this._deviceOrientationCamera;
  91925. },
  91926. enumerable: true,
  91927. configurable: true
  91928. });
  91929. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91930. /**
  91931. * Based on the current WebVR support, returns the current VR camera used.
  91932. */
  91933. get: function () {
  91934. if (this._webVRready) {
  91935. return this._webVRCamera;
  91936. }
  91937. else {
  91938. return this._scene.activeCamera;
  91939. }
  91940. },
  91941. enumerable: true,
  91942. configurable: true
  91943. });
  91944. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91945. /**
  91946. * The webVRCamera which is used when in VR.
  91947. */
  91948. get: function () {
  91949. return this._webVRCamera;
  91950. },
  91951. enumerable: true,
  91952. configurable: true
  91953. });
  91954. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91955. /**
  91956. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91957. */
  91958. get: function () {
  91959. return this._vrDeviceOrientationCamera;
  91960. },
  91961. enumerable: true,
  91962. configurable: true
  91963. });
  91964. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91965. get: function () {
  91966. var result = this._cameraGazer._teleportationRequestInitiated
  91967. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91968. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91969. return result;
  91970. },
  91971. enumerable: true,
  91972. configurable: true
  91973. });
  91974. // Raised when one of the controller has loaded successfully its associated default mesh
  91975. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91976. if (this.leftController && this.leftController.webVRController == webVRController) {
  91977. if (webVRController.mesh) {
  91978. this.leftController._setLaserPointerParent(webVRController.mesh);
  91979. }
  91980. }
  91981. if (this.rightController && this.rightController.webVRController == webVRController) {
  91982. if (webVRController.mesh) {
  91983. this.rightController._setLaserPointerParent(webVRController.mesh);
  91984. }
  91985. }
  91986. try {
  91987. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91988. }
  91989. catch (err) {
  91990. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91991. }
  91992. };
  91993. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91994. /**
  91995. * Gets a value indicating if we are currently in VR mode.
  91996. */
  91997. get: function () {
  91998. return this._webVRpresenting || this._fullscreenVRpresenting;
  91999. },
  92000. enumerable: true,
  92001. configurable: true
  92002. });
  92003. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92004. var vrDisplay = this._scene.getEngine().getVRDevice();
  92005. if (vrDisplay) {
  92006. var wasPresenting = this._webVRpresenting;
  92007. // A VR display is connected
  92008. this._webVRpresenting = vrDisplay.isPresenting;
  92009. if (wasPresenting && !this._webVRpresenting)
  92010. this.exitVR();
  92011. }
  92012. else {
  92013. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92014. }
  92015. this.updateButtonVisibility();
  92016. };
  92017. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92018. this._webVRsupported = eventArgs.vrSupported;
  92019. this._webVRready = !!eventArgs.vrDisplay;
  92020. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92021. this.updateButtonVisibility();
  92022. };
  92023. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92024. if (this._canvas && !this._useCustomVRButton) {
  92025. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92026. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92027. }
  92028. };
  92029. VRExperienceHelper.prototype.displayVRButton = function () {
  92030. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92031. document.body.appendChild(this._btnVR);
  92032. this._btnVRDisplayed = true;
  92033. }
  92034. };
  92035. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92036. if (!this._btnVR || this._useCustomVRButton) {
  92037. return;
  92038. }
  92039. this._btnVR.className = "babylonVRicon";
  92040. if (this.isInVRMode) {
  92041. this._btnVR.className += " vrdisplaypresenting";
  92042. }
  92043. else {
  92044. if (this._webVRready)
  92045. this._btnVR.className += " vrdisplayready";
  92046. if (this._webVRsupported)
  92047. this._btnVR.className += " vrdisplaysupported";
  92048. if (this._webVRrequesting)
  92049. this._btnVR.className += " vrdisplayrequesting";
  92050. }
  92051. };
  92052. /**
  92053. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92054. * Otherwise, will use the fullscreen API.
  92055. */
  92056. VRExperienceHelper.prototype.enterVR = function () {
  92057. if (this.onEnteringVRObservable) {
  92058. try {
  92059. this.onEnteringVRObservable.notifyObservers(this);
  92060. }
  92061. catch (err) {
  92062. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92063. }
  92064. }
  92065. if (this._scene.activeCamera) {
  92066. this._position = this._scene.activeCamera.position.clone();
  92067. // make sure that we return to the last active camera
  92068. this._existingCamera = this._scene.activeCamera;
  92069. }
  92070. if (this._webVRrequesting)
  92071. return;
  92072. // If WebVR is supported and a headset is connected
  92073. if (this._webVRready) {
  92074. if (!this._webVRpresenting) {
  92075. this._webVRCamera.position = this._position;
  92076. this._scene.activeCamera = this._webVRCamera;
  92077. }
  92078. }
  92079. else if (this._vrDeviceOrientationCamera) {
  92080. this._vrDeviceOrientationCamera.position = this._position;
  92081. if (this._scene.activeCamera) {
  92082. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92083. }
  92084. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92085. this._scene.getEngine().switchFullscreen(true);
  92086. this.updateButtonVisibility();
  92087. }
  92088. if (this._scene.activeCamera && this._canvas) {
  92089. this._scene.activeCamera.attachControl(this._canvas);
  92090. }
  92091. if (this._interactionsEnabled) {
  92092. this._scene.registerBeforeRender(this.beforeRender);
  92093. }
  92094. };
  92095. /**
  92096. * Attempt to exit VR, or fullscreen.
  92097. */
  92098. VRExperienceHelper.prototype.exitVR = function () {
  92099. if (this.onExitingVRObservable) {
  92100. try {
  92101. this.onExitingVRObservable.notifyObservers(this);
  92102. }
  92103. catch (err) {
  92104. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92105. }
  92106. }
  92107. if (this._webVRpresenting) {
  92108. this._scene.getEngine().disableVR();
  92109. }
  92110. if (this._scene.activeCamera) {
  92111. this._position = this._scene.activeCamera.position.clone();
  92112. }
  92113. if (this._deviceOrientationCamera) {
  92114. this._deviceOrientationCamera.position = this._position;
  92115. this._scene.activeCamera = this._deviceOrientationCamera;
  92116. if (this._canvas) {
  92117. this._scene.activeCamera.attachControl(this._canvas);
  92118. }
  92119. }
  92120. else if (this._existingCamera) {
  92121. this._existingCamera.position = this._position;
  92122. this._scene.activeCamera = this._existingCamera;
  92123. }
  92124. this.updateButtonVisibility();
  92125. if (this._interactionsEnabled) {
  92126. this._scene.unregisterBeforeRender(this.beforeRender);
  92127. }
  92128. // resize to update width and height when exiting vr exits fullscreen
  92129. this._scene.getEngine().resize();
  92130. };
  92131. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92132. /**
  92133. * The position of the vr experience helper.
  92134. */
  92135. get: function () {
  92136. return this._position;
  92137. },
  92138. /**
  92139. * Sets the position of the vr experience helper.
  92140. */
  92141. set: function (value) {
  92142. this._position = value;
  92143. if (this._scene.activeCamera) {
  92144. this._scene.activeCamera.position = value;
  92145. }
  92146. },
  92147. enumerable: true,
  92148. configurable: true
  92149. });
  92150. /**
  92151. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92152. */
  92153. VRExperienceHelper.prototype.enableInteractions = function () {
  92154. var _this = this;
  92155. if (!this._interactionsEnabled) {
  92156. this._interactionsRequested = true;
  92157. if (this.leftController) {
  92158. this._enableInteractionOnController(this.leftController);
  92159. }
  92160. if (this.rightController) {
  92161. this._enableInteractionOnController(this.rightController);
  92162. }
  92163. this.raySelectionPredicate = function (mesh) {
  92164. return mesh.isVisible;
  92165. };
  92166. this.meshSelectionPredicate = function (mesh) {
  92167. return true;
  92168. };
  92169. this._raySelectionPredicate = function (mesh) {
  92170. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92171. && mesh.name.indexOf("teleportationTarget") === -1
  92172. && mesh.name.indexOf("torusTeleportation") === -1
  92173. && mesh.name.indexOf("laserPointer") === -1)) {
  92174. return _this.raySelectionPredicate(mesh);
  92175. }
  92176. return false;
  92177. };
  92178. this._interactionsEnabled = true;
  92179. }
  92180. };
  92181. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92182. get: function () {
  92183. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92184. },
  92185. enumerable: true,
  92186. configurable: true
  92187. });
  92188. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92189. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92190. if (this._floorMeshesCollection[i].id === mesh.id) {
  92191. return true;
  92192. }
  92193. }
  92194. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92195. return true;
  92196. }
  92197. return false;
  92198. };
  92199. /**
  92200. * Adds a floor mesh to be used for teleportation.
  92201. * @param floorMesh the mesh to be used for teleportation.
  92202. */
  92203. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92204. if (!this._floorMeshesCollection) {
  92205. return;
  92206. }
  92207. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92208. return;
  92209. }
  92210. this._floorMeshesCollection.push(floorMesh);
  92211. };
  92212. /**
  92213. * Removes a floor mesh from being used for teleportation.
  92214. * @param floorMesh the mesh to be removed.
  92215. */
  92216. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92217. if (!this._floorMeshesCollection) {
  92218. return;
  92219. }
  92220. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92221. if (meshIndex !== -1) {
  92222. this._floorMeshesCollection.splice(meshIndex, 1);
  92223. }
  92224. };
  92225. /**
  92226. * Enables interactions and teleportation using the VR controllers and gaze.
  92227. * @param vrTeleportationOptions options to modify teleportation behavior.
  92228. */
  92229. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92230. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92231. if (!this._teleportationInitialized) {
  92232. this._teleportationRequested = true;
  92233. this.enableInteractions();
  92234. if (vrTeleportationOptions.floorMeshName) {
  92235. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92236. }
  92237. if (vrTeleportationOptions.floorMeshes) {
  92238. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92239. }
  92240. if (this.leftController != null) {
  92241. this._enableTeleportationOnController(this.leftController);
  92242. }
  92243. if (this.rightController != null) {
  92244. this._enableTeleportationOnController(this.rightController);
  92245. }
  92246. // Creates an image processing post process for the vignette not relying
  92247. // on the main scene configuration for image processing to reduce setup and spaces
  92248. // (gamma/linear) conflicts.
  92249. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92250. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92251. imageProcessingConfiguration.vignetteEnabled = true;
  92252. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92253. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92254. this._teleportationInitialized = true;
  92255. if (this._isDefaultTeleportationTarget) {
  92256. this._createTeleportationCircles();
  92257. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92258. }
  92259. }
  92260. };
  92261. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92262. var _this = this;
  92263. var controllerMesh = controller.webVRController.mesh;
  92264. if (controllerMesh) {
  92265. controller._interactionsEnabled = true;
  92266. controller._activatePointer();
  92267. if (this.webVROptions.laserToggle) {
  92268. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92269. // Enabling / disabling laserPointer
  92270. if (_this._displayLaserPointer && stateObject.value === 1) {
  92271. if (controller._activePointer) {
  92272. controller._deactivatePointer();
  92273. }
  92274. else {
  92275. controller._activatePointer();
  92276. }
  92277. if (_this.displayGaze) {
  92278. controller._gazeTracker.isVisible = controller._activePointer;
  92279. }
  92280. }
  92281. });
  92282. }
  92283. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92284. var gazer = controller;
  92285. if (_this._noControllerIsActive) {
  92286. gazer = _this._cameraGazer;
  92287. }
  92288. if (!gazer._pointerDownOnMeshAsked) {
  92289. if (stateObject.value > _this._padSensibilityUp) {
  92290. gazer._selectionPointerDown();
  92291. }
  92292. }
  92293. else if (stateObject.value < _this._padSensibilityDown) {
  92294. gazer._selectionPointerUp();
  92295. }
  92296. });
  92297. }
  92298. };
  92299. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92300. // Dont teleport if another gaze already requested teleportation
  92301. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92302. return;
  92303. }
  92304. if (!gazer._teleportationRequestInitiated) {
  92305. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92306. gazer._activatePointer();
  92307. gazer._teleportationRequestInitiated = true;
  92308. }
  92309. }
  92310. else {
  92311. // Listening to the proper controller values changes to confirm teleportation
  92312. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92313. if (this._teleportActive) {
  92314. this._teleportCamera(this._haloCenter);
  92315. }
  92316. gazer._teleportationRequestInitiated = false;
  92317. }
  92318. }
  92319. };
  92320. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92321. // Only rotate when user is not currently selecting a teleportation location
  92322. if (gazer._teleportationRequestInitiated) {
  92323. return;
  92324. }
  92325. if (!gazer._rotationLeftAsked) {
  92326. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92327. gazer._rotationLeftAsked = true;
  92328. if (this._rotationAllowed) {
  92329. this._rotateCamera(false);
  92330. }
  92331. }
  92332. }
  92333. else {
  92334. if (stateObject.x > -this._padSensibilityDown) {
  92335. gazer._rotationLeftAsked = false;
  92336. }
  92337. }
  92338. if (!gazer._rotationRightAsked) {
  92339. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92340. gazer._rotationRightAsked = true;
  92341. if (this._rotationAllowed) {
  92342. this._rotateCamera(true);
  92343. }
  92344. }
  92345. }
  92346. else {
  92347. if (stateObject.x < this._padSensibilityDown) {
  92348. gazer._rotationRightAsked = false;
  92349. }
  92350. }
  92351. };
  92352. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92353. // Only teleport backwards when user is not currently selecting a teleportation location
  92354. if (gazer._teleportationRequestInitiated) {
  92355. return;
  92356. }
  92357. // Teleport backwards
  92358. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92359. if (!gazer._teleportationBackRequestInitiated) {
  92360. if (!this.currentVRCamera) {
  92361. return;
  92362. }
  92363. // Get rotation and position of the current camera
  92364. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92365. var position = this.currentVRCamera.position;
  92366. // If the camera has device position, use that instead
  92367. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92368. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92369. position = this.currentVRCamera.devicePosition;
  92370. }
  92371. // Get matrix with only the y rotation of the device rotation
  92372. rotation.toEulerAnglesToRef(this._workingVector);
  92373. this._workingVector.z = 0;
  92374. this._workingVector.x = 0;
  92375. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92376. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92377. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92378. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92379. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92380. var ray = new BABYLON.Ray(position, this._workingVector);
  92381. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92382. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92383. this._teleportCamera(hit.pickedPoint);
  92384. }
  92385. gazer._teleportationBackRequestInitiated = true;
  92386. }
  92387. }
  92388. else {
  92389. gazer._teleportationBackRequestInitiated = false;
  92390. }
  92391. };
  92392. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92393. var _this = this;
  92394. var controllerMesh = controller.webVRController.mesh;
  92395. if (controllerMesh) {
  92396. if (!controller._interactionsEnabled) {
  92397. this._enableInteractionOnController(controller);
  92398. }
  92399. controller._interactionsEnabled = true;
  92400. controller._teleportationEnabled = true;
  92401. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92402. controller._dpadPressed = false;
  92403. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92404. controller._dpadPressed = stateObject.pressed;
  92405. if (!controller._dpadPressed) {
  92406. controller._rotationLeftAsked = false;
  92407. controller._rotationRightAsked = false;
  92408. controller._teleportationBackRequestInitiated = false;
  92409. }
  92410. });
  92411. }
  92412. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92413. if (_this.teleportationEnabled) {
  92414. _this._checkTeleportBackwards(stateObject, controller);
  92415. _this._checkTeleportWithRay(stateObject, controller);
  92416. }
  92417. _this._checkRotate(stateObject, controller);
  92418. });
  92419. }
  92420. };
  92421. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92422. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92423. this._teleportationTarget.isPickable = false;
  92424. var length = 512;
  92425. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92426. dynamicTexture.hasAlpha = true;
  92427. var context = dynamicTexture.getContext();
  92428. var centerX = length / 2;
  92429. var centerY = length / 2;
  92430. var radius = 200;
  92431. context.beginPath();
  92432. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92433. context.fillStyle = this._teleportationFillColor;
  92434. context.fill();
  92435. context.lineWidth = 10;
  92436. context.strokeStyle = this._teleportationBorderColor;
  92437. context.stroke();
  92438. context.closePath();
  92439. dynamicTexture.update();
  92440. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92441. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92442. this._teleportationTarget.material = teleportationCircleMaterial;
  92443. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92444. torus.isPickable = false;
  92445. torus.parent = this._teleportationTarget;
  92446. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92447. var keys = [];
  92448. keys.push({
  92449. frame: 0,
  92450. value: 0
  92451. });
  92452. keys.push({
  92453. frame: 30,
  92454. value: 0.4
  92455. });
  92456. keys.push({
  92457. frame: 60,
  92458. value: 0
  92459. });
  92460. animationInnerCircle.setKeys(keys);
  92461. var easingFunction = new BABYLON.SineEase();
  92462. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92463. animationInnerCircle.setEasingFunction(easingFunction);
  92464. torus.animations = [];
  92465. torus.animations.push(animationInnerCircle);
  92466. this._scene.beginAnimation(torus, 0, 60, true);
  92467. this._hideTeleportationTarget();
  92468. };
  92469. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92470. this._teleportActive = true;
  92471. if (this._teleportationInitialized) {
  92472. this._teleportationTarget.isVisible = true;
  92473. if (this._isDefaultTeleportationTarget) {
  92474. this._teleportationTarget.getChildren()[0].isVisible = true;
  92475. }
  92476. }
  92477. };
  92478. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92479. this._teleportActive = false;
  92480. if (this._teleportationInitialized) {
  92481. this._teleportationTarget.isVisible = false;
  92482. if (this._isDefaultTeleportationTarget) {
  92483. this._teleportationTarget.getChildren()[0].isVisible = false;
  92484. }
  92485. }
  92486. };
  92487. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92488. var _this = this;
  92489. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92490. return;
  92491. }
  92492. if (right) {
  92493. this._rotationAngle++;
  92494. }
  92495. else {
  92496. this._rotationAngle--;
  92497. }
  92498. this.currentVRCamera.animations = [];
  92499. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92500. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92501. var animationRotationKeys = [];
  92502. animationRotationKeys.push({
  92503. frame: 0,
  92504. value: this.currentVRCamera.rotationQuaternion
  92505. });
  92506. animationRotationKeys.push({
  92507. frame: 6,
  92508. value: target
  92509. });
  92510. animationRotation.setKeys(animationRotationKeys);
  92511. animationRotation.setEasingFunction(this._circleEase);
  92512. this.currentVRCamera.animations.push(animationRotation);
  92513. this._postProcessMove.animations = [];
  92514. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92515. var vignetteWeightKeys = [];
  92516. vignetteWeightKeys.push({
  92517. frame: 0,
  92518. value: 0
  92519. });
  92520. vignetteWeightKeys.push({
  92521. frame: 3,
  92522. value: 4
  92523. });
  92524. vignetteWeightKeys.push({
  92525. frame: 6,
  92526. value: 0
  92527. });
  92528. animationPP.setKeys(vignetteWeightKeys);
  92529. animationPP.setEasingFunction(this._circleEase);
  92530. this._postProcessMove.animations.push(animationPP);
  92531. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92532. var vignetteStretchKeys = [];
  92533. vignetteStretchKeys.push({
  92534. frame: 0,
  92535. value: 0
  92536. });
  92537. vignetteStretchKeys.push({
  92538. frame: 3,
  92539. value: 10
  92540. });
  92541. vignetteStretchKeys.push({
  92542. frame: 6,
  92543. value: 0
  92544. });
  92545. animationPP2.setKeys(vignetteStretchKeys);
  92546. animationPP2.setEasingFunction(this._circleEase);
  92547. this._postProcessMove.animations.push(animationPP2);
  92548. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92549. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92550. this._postProcessMove.samples = 4;
  92551. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92552. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92553. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92554. });
  92555. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92556. };
  92557. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92558. if (hit.pickedPoint) {
  92559. if (gazer._teleportationRequestInitiated) {
  92560. this._displayTeleportationTarget();
  92561. this._haloCenter.copyFrom(hit.pickedPoint);
  92562. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92563. }
  92564. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92565. if (pickNormal) {
  92566. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92567. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92568. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92569. }
  92570. this._teleportationTarget.position.y += 0.1;
  92571. }
  92572. };
  92573. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92574. var _this = this;
  92575. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92576. return;
  92577. }
  92578. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92579. // offset of the headset from the anchor.
  92580. if (this.webVRCamera.leftCamera) {
  92581. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92582. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92583. location.subtractToRef(this._workingVector, this._workingVector);
  92584. }
  92585. else {
  92586. this._workingVector.copyFrom(location);
  92587. }
  92588. // Add height to account for user's height offset
  92589. if (this.isInVRMode) {
  92590. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92591. }
  92592. else {
  92593. this._workingVector.y += this._defaultHeight;
  92594. }
  92595. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92596. // Create animation from the camera's position to the new location
  92597. this.currentVRCamera.animations = [];
  92598. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92599. var animationCameraTeleportationKeys = [{
  92600. frame: 0,
  92601. value: this.currentVRCamera.position
  92602. },
  92603. {
  92604. frame: 11,
  92605. value: this._workingVector
  92606. }
  92607. ];
  92608. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92609. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92610. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92611. this._postProcessMove.animations = [];
  92612. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92613. var vignetteWeightKeys = [];
  92614. vignetteWeightKeys.push({
  92615. frame: 0,
  92616. value: 0
  92617. });
  92618. vignetteWeightKeys.push({
  92619. frame: 5,
  92620. value: 8
  92621. });
  92622. vignetteWeightKeys.push({
  92623. frame: 11,
  92624. value: 0
  92625. });
  92626. animationPP.setKeys(vignetteWeightKeys);
  92627. this._postProcessMove.animations.push(animationPP);
  92628. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92629. var vignetteStretchKeys = [];
  92630. vignetteStretchKeys.push({
  92631. frame: 0,
  92632. value: 0
  92633. });
  92634. vignetteStretchKeys.push({
  92635. frame: 5,
  92636. value: 10
  92637. });
  92638. vignetteStretchKeys.push({
  92639. frame: 11,
  92640. value: 0
  92641. });
  92642. animationPP2.setKeys(vignetteStretchKeys);
  92643. this._postProcessMove.animations.push(animationPP2);
  92644. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92645. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92646. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92647. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92648. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92649. });
  92650. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92651. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92652. });
  92653. this._hideTeleportationTarget();
  92654. };
  92655. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92656. if (normal) {
  92657. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92658. if (angle < Math.PI / 2) {
  92659. normal.scaleInPlace(-1);
  92660. }
  92661. }
  92662. return normal;
  92663. };
  92664. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92665. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92666. return;
  92667. }
  92668. var ray = gazer._getForwardRay(this._rayLength);
  92669. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92670. if (hit) {
  92671. // Populate the contrllers mesh that can be used for drag/drop
  92672. if (gazer._laserPointer) {
  92673. hit.originMesh = gazer._laserPointer.parent;
  92674. }
  92675. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92676. }
  92677. gazer._currentHit = hit;
  92678. // Moving the gazeTracker on the mesh face targetted
  92679. if (hit && hit.pickedPoint) {
  92680. if (this._displayGaze) {
  92681. var multiplier = 1;
  92682. gazer._gazeTracker.isVisible = true;
  92683. if (gazer._isActionableMesh) {
  92684. multiplier = 3;
  92685. }
  92686. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92687. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92688. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92689. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92690. // To avoid z-fighting
  92691. var deltaFighting = 0.002;
  92692. if (pickNormal) {
  92693. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92694. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92695. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92696. }
  92697. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92698. if (gazer._gazeTracker.position.x < 0) {
  92699. gazer._gazeTracker.position.x += deltaFighting;
  92700. }
  92701. else {
  92702. gazer._gazeTracker.position.x -= deltaFighting;
  92703. }
  92704. if (gazer._gazeTracker.position.y < 0) {
  92705. gazer._gazeTracker.position.y += deltaFighting;
  92706. }
  92707. else {
  92708. gazer._gazeTracker.position.y -= deltaFighting;
  92709. }
  92710. if (gazer._gazeTracker.position.z < 0) {
  92711. gazer._gazeTracker.position.z += deltaFighting;
  92712. }
  92713. else {
  92714. gazer._gazeTracker.position.z -= deltaFighting;
  92715. }
  92716. }
  92717. // Changing the size of the laser pointer based on the distance from the targetted point
  92718. gazer._updatePointerDistance(hit.distance);
  92719. }
  92720. else {
  92721. gazer._updatePointerDistance();
  92722. gazer._gazeTracker.isVisible = false;
  92723. }
  92724. if (hit && hit.pickedMesh) {
  92725. // The object selected is the floor, we're in a teleportation scenario
  92726. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92727. // Moving the teleportation area to this targetted point
  92728. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92729. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92730. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92731. }
  92732. gazer._currentMeshSelected = null;
  92733. if (gazer._teleportationRequestInitiated) {
  92734. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92735. }
  92736. return;
  92737. }
  92738. // If not, we're in a selection scenario
  92739. //this._teleportationAllowed = false;
  92740. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92741. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92742. this.onNewMeshPicked.notifyObservers(hit);
  92743. gazer._currentMeshSelected = hit.pickedMesh;
  92744. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92745. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92746. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92747. gazer._isActionableMesh = true;
  92748. }
  92749. else {
  92750. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92751. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92752. gazer._isActionableMesh = false;
  92753. }
  92754. try {
  92755. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92756. }
  92757. catch (err) {
  92758. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92759. }
  92760. }
  92761. else {
  92762. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92763. gazer._currentMeshSelected = null;
  92764. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92765. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92766. }
  92767. }
  92768. }
  92769. else {
  92770. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92771. gazer._currentMeshSelected = null;
  92772. //this._teleportationAllowed = false;
  92773. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92774. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92775. }
  92776. };
  92777. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92778. if (mesh) {
  92779. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92780. }
  92781. };
  92782. /**
  92783. * Sets the color of the laser ray from the vr controllers.
  92784. * @param color new color for the ray.
  92785. */
  92786. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92787. if (this.leftController) {
  92788. this.leftController._setLaserPointerColor(color);
  92789. }
  92790. if (this.rightController) {
  92791. this.rightController._setLaserPointerColor(color);
  92792. }
  92793. };
  92794. /**
  92795. * Sets the color of the ray from the vr headsets gaze.
  92796. * @param color new color for the ray.
  92797. */
  92798. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92799. if (!this._cameraGazer._gazeTracker.material) {
  92800. return;
  92801. }
  92802. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92803. if (this.leftController) {
  92804. this.leftController._gazeTracker.material.emissiveColor = color;
  92805. }
  92806. if (this.rightController) {
  92807. this.rightController._gazeTracker.material.emissiveColor = color;
  92808. }
  92809. };
  92810. /**
  92811. * Exits VR and disposes of the vr experience helper
  92812. */
  92813. VRExperienceHelper.prototype.dispose = function () {
  92814. if (this.isInVRMode) {
  92815. this.exitVR();
  92816. }
  92817. if (this._postProcessMove) {
  92818. this._postProcessMove.dispose();
  92819. }
  92820. if (this._webVRCamera) {
  92821. this._webVRCamera.dispose();
  92822. }
  92823. if (this._vrDeviceOrientationCamera) {
  92824. this._vrDeviceOrientationCamera.dispose();
  92825. }
  92826. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92827. document.body.removeChild(this._btnVR);
  92828. }
  92829. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92830. this._deviceOrientationCamera.dispose();
  92831. }
  92832. if (this._cameraGazer) {
  92833. this._cameraGazer.dispose();
  92834. }
  92835. if (this.leftController) {
  92836. this.leftController.dispose();
  92837. }
  92838. if (this.rightController) {
  92839. this.rightController.dispose();
  92840. }
  92841. if (this._teleportationTarget) {
  92842. this._teleportationTarget.dispose();
  92843. }
  92844. this._floorMeshesCollection = [];
  92845. document.removeEventListener("keydown", this._onKeyDown);
  92846. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92847. window.removeEventListener("resize", this._onResize);
  92848. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92849. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92850. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92851. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92852. document.onmsfullscreenchange = null;
  92853. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92854. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92855. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92856. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92857. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92858. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92859. this._scene.unregisterBeforeRender(this.beforeRender);
  92860. };
  92861. /**
  92862. * Gets the name of the VRExperienceHelper class
  92863. * @returns "VRExperienceHelper"
  92864. */
  92865. VRExperienceHelper.prototype.getClassName = function () {
  92866. return "VRExperienceHelper";
  92867. };
  92868. return VRExperienceHelper;
  92869. }());
  92870. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92871. })(BABYLON || (BABYLON = {}));
  92872. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92873. // Mainly based on these 2 articles :
  92874. // 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
  92875. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92876. var BABYLON;
  92877. (function (BABYLON) {
  92878. /**
  92879. * Defines the potential axis of a Joystick
  92880. */
  92881. var JoystickAxis;
  92882. (function (JoystickAxis) {
  92883. /** X axis */
  92884. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92885. /** Y axis */
  92886. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92887. /** Z axis */
  92888. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92889. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92890. /**
  92891. * Class used to define virtual joystick (used in touch mode)
  92892. */
  92893. var VirtualJoystick = /** @class */ (function () {
  92894. /**
  92895. * Creates a new virtual joystick
  92896. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92897. */
  92898. function VirtualJoystick(leftJoystick) {
  92899. var _this = this;
  92900. if (leftJoystick) {
  92901. this._leftJoystick = true;
  92902. }
  92903. else {
  92904. this._leftJoystick = false;
  92905. }
  92906. VirtualJoystick._globalJoystickIndex++;
  92907. // By default left & right arrow keys are moving the X
  92908. // and up & down keys are moving the Y
  92909. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92910. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92911. this.reverseLeftRight = false;
  92912. this.reverseUpDown = false;
  92913. // collections of pointers
  92914. this._touches = new BABYLON.StringDictionary();
  92915. this.deltaPosition = BABYLON.Vector3.Zero();
  92916. this._joystickSensibility = 25;
  92917. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92918. this._onResize = function (evt) {
  92919. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92920. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92921. if (VirtualJoystick.vjCanvas) {
  92922. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92923. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92924. }
  92925. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92926. };
  92927. // injecting a canvas element on top of the canvas 3D game
  92928. if (!VirtualJoystick.vjCanvas) {
  92929. window.addEventListener("resize", this._onResize, false);
  92930. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92931. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92932. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92933. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92934. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92935. VirtualJoystick.vjCanvas.style.width = "100%";
  92936. VirtualJoystick.vjCanvas.style.height = "100%";
  92937. VirtualJoystick.vjCanvas.style.position = "absolute";
  92938. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92939. VirtualJoystick.vjCanvas.style.top = "0px";
  92940. VirtualJoystick.vjCanvas.style.left = "0px";
  92941. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92942. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92943. // Support for jQuery PEP polyfill
  92944. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92945. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92946. if (!context) {
  92947. throw new Error("Unable to create canvas for virtual joystick");
  92948. }
  92949. VirtualJoystick.vjCanvasContext = context;
  92950. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92951. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92952. document.body.appendChild(VirtualJoystick.vjCanvas);
  92953. }
  92954. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92955. this.pressed = false;
  92956. // default joystick color
  92957. this._joystickColor = "cyan";
  92958. this._joystickPointerID = -1;
  92959. // current joystick position
  92960. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92961. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92962. // origin joystick position
  92963. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92964. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92965. this._onPointerDownHandlerRef = function (evt) {
  92966. _this._onPointerDown(evt);
  92967. };
  92968. this._onPointerMoveHandlerRef = function (evt) {
  92969. _this._onPointerMove(evt);
  92970. };
  92971. this._onPointerUpHandlerRef = function (evt) {
  92972. _this._onPointerUp(evt);
  92973. };
  92974. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92975. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92976. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92977. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92978. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92979. evt.preventDefault(); // Disables system menu
  92980. }, false);
  92981. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92982. }
  92983. /**
  92984. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92985. * @param newJoystickSensibility defines the new sensibility
  92986. */
  92987. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92988. this._joystickSensibility = newJoystickSensibility;
  92989. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92990. };
  92991. VirtualJoystick.prototype._onPointerDown = function (e) {
  92992. var positionOnScreenCondition;
  92993. e.preventDefault();
  92994. if (this._leftJoystick === true) {
  92995. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92996. }
  92997. else {
  92998. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92999. }
  93000. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93001. // First contact will be dedicated to the virtual joystick
  93002. this._joystickPointerID = e.pointerId;
  93003. this._joystickPointerStartPos.x = e.clientX;
  93004. this._joystickPointerStartPos.y = e.clientY;
  93005. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93006. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93007. this._deltaJoystickVector.x = 0;
  93008. this._deltaJoystickVector.y = 0;
  93009. this.pressed = true;
  93010. this._touches.add(e.pointerId.toString(), e);
  93011. }
  93012. else {
  93013. // You can only trigger the action buttons with a joystick declared
  93014. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93015. this._action();
  93016. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93017. }
  93018. }
  93019. };
  93020. VirtualJoystick.prototype._onPointerMove = function (e) {
  93021. // If the current pointer is the one associated to the joystick (first touch contact)
  93022. if (this._joystickPointerID == e.pointerId) {
  93023. this._joystickPointerPos.x = e.clientX;
  93024. this._joystickPointerPos.y = e.clientY;
  93025. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93026. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93027. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93028. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93029. switch (this._axisTargetedByLeftAndRight) {
  93030. case JoystickAxis.X:
  93031. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93032. break;
  93033. case JoystickAxis.Y:
  93034. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93035. break;
  93036. case JoystickAxis.Z:
  93037. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93038. break;
  93039. }
  93040. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93041. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93042. switch (this._axisTargetedByUpAndDown) {
  93043. case JoystickAxis.X:
  93044. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93045. break;
  93046. case JoystickAxis.Y:
  93047. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93048. break;
  93049. case JoystickAxis.Z:
  93050. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93051. break;
  93052. }
  93053. }
  93054. else {
  93055. var data = this._touches.get(e.pointerId.toString());
  93056. if (data) {
  93057. data.x = e.clientX;
  93058. data.y = e.clientY;
  93059. }
  93060. }
  93061. };
  93062. VirtualJoystick.prototype._onPointerUp = function (e) {
  93063. if (this._joystickPointerID == e.pointerId) {
  93064. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93065. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93066. this._joystickPointerID = -1;
  93067. this.pressed = false;
  93068. }
  93069. else {
  93070. var touch = this._touches.get(e.pointerId.toString());
  93071. if (touch) {
  93072. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93073. }
  93074. }
  93075. this._deltaJoystickVector.x = 0;
  93076. this._deltaJoystickVector.y = 0;
  93077. this._touches.remove(e.pointerId.toString());
  93078. };
  93079. /**
  93080. * Change the color of the virtual joystick
  93081. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93082. */
  93083. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93084. this._joystickColor = newColor;
  93085. };
  93086. /**
  93087. * Defines a callback to call when the joystick is touched
  93088. * @param action defines the callback
  93089. */
  93090. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93091. this._action = action;
  93092. };
  93093. /**
  93094. * Defines which axis you'd like to control for left & right
  93095. * @param axis defines the axis to use
  93096. */
  93097. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93098. switch (axis) {
  93099. case JoystickAxis.X:
  93100. case JoystickAxis.Y:
  93101. case JoystickAxis.Z:
  93102. this._axisTargetedByLeftAndRight = axis;
  93103. break;
  93104. default:
  93105. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93106. break;
  93107. }
  93108. };
  93109. /**
  93110. * Defines which axis you'd like to control for up & down
  93111. * @param axis defines the axis to use
  93112. */
  93113. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93114. switch (axis) {
  93115. case JoystickAxis.X:
  93116. case JoystickAxis.Y:
  93117. case JoystickAxis.Z:
  93118. this._axisTargetedByUpAndDown = axis;
  93119. break;
  93120. default:
  93121. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93122. break;
  93123. }
  93124. };
  93125. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93126. var _this = this;
  93127. if (this.pressed) {
  93128. this._touches.forEach(function (key, touch) {
  93129. if (touch.pointerId === _this._joystickPointerID) {
  93130. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93131. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93132. VirtualJoystick.vjCanvasContext.beginPath();
  93133. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93134. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93135. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93136. VirtualJoystick.vjCanvasContext.stroke();
  93137. VirtualJoystick.vjCanvasContext.closePath();
  93138. VirtualJoystick.vjCanvasContext.beginPath();
  93139. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93140. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93141. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93142. VirtualJoystick.vjCanvasContext.stroke();
  93143. VirtualJoystick.vjCanvasContext.closePath();
  93144. VirtualJoystick.vjCanvasContext.beginPath();
  93145. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93146. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93147. VirtualJoystick.vjCanvasContext.stroke();
  93148. VirtualJoystick.vjCanvasContext.closePath();
  93149. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93150. }
  93151. else {
  93152. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93153. VirtualJoystick.vjCanvasContext.beginPath();
  93154. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93155. VirtualJoystick.vjCanvasContext.beginPath();
  93156. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93157. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93158. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93159. VirtualJoystick.vjCanvasContext.stroke();
  93160. VirtualJoystick.vjCanvasContext.closePath();
  93161. touch.prevX = touch.x;
  93162. touch.prevY = touch.y;
  93163. }
  93164. ;
  93165. });
  93166. }
  93167. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93168. };
  93169. /**
  93170. * Release internal HTML canvas
  93171. */
  93172. VirtualJoystick.prototype.releaseCanvas = function () {
  93173. if (VirtualJoystick.vjCanvas) {
  93174. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93175. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93176. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93177. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93178. window.removeEventListener("resize", this._onResize);
  93179. document.body.removeChild(VirtualJoystick.vjCanvas);
  93180. VirtualJoystick.vjCanvas = null;
  93181. }
  93182. };
  93183. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93184. VirtualJoystick._globalJoystickIndex = 0;
  93185. return VirtualJoystick;
  93186. }());
  93187. BABYLON.VirtualJoystick = VirtualJoystick;
  93188. })(BABYLON || (BABYLON = {}));
  93189. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93190. var BABYLON;
  93191. (function (BABYLON) {
  93192. // We're mainly based on the logic defined into the FreeCamera code
  93193. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93194. __extends(VirtualJoysticksCamera, _super);
  93195. function VirtualJoysticksCamera(name, position, scene) {
  93196. var _this = _super.call(this, name, position, scene) || this;
  93197. _this.inputs.addVirtualJoystick();
  93198. return _this;
  93199. }
  93200. VirtualJoysticksCamera.prototype.getClassName = function () {
  93201. return "VirtualJoysticksCamera";
  93202. };
  93203. return VirtualJoysticksCamera;
  93204. }(BABYLON.FreeCamera));
  93205. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93206. })(BABYLON || (BABYLON = {}));
  93207. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93208. var BABYLON;
  93209. (function (BABYLON) {
  93210. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93211. function FreeCameraVirtualJoystickInput() {
  93212. }
  93213. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93214. return this._leftjoystick;
  93215. };
  93216. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93217. return this._rightjoystick;
  93218. };
  93219. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93220. if (this._leftjoystick) {
  93221. var camera = this.camera;
  93222. var speed = camera._computeLocalCameraSpeed() * 50;
  93223. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93224. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93225. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93226. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93227. if (!this._leftjoystick.pressed) {
  93228. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93229. }
  93230. if (!this._rightjoystick.pressed) {
  93231. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93232. }
  93233. }
  93234. };
  93235. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93236. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93237. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93238. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93239. this._leftjoystick.setJoystickSensibility(0.15);
  93240. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93241. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93242. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93243. this._rightjoystick.reverseUpDown = true;
  93244. this._rightjoystick.setJoystickSensibility(0.05);
  93245. this._rightjoystick.setJoystickColor("yellow");
  93246. };
  93247. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93248. this._leftjoystick.releaseCanvas();
  93249. this._rightjoystick.releaseCanvas();
  93250. };
  93251. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93252. return "FreeCameraVirtualJoystickInput";
  93253. };
  93254. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93255. return "virtualJoystick";
  93256. };
  93257. return FreeCameraVirtualJoystickInput;
  93258. }());
  93259. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93260. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93261. })(BABYLON || (BABYLON = {}));
  93262. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93263. var BABYLON;
  93264. (function (BABYLON) {
  93265. var SimplificationSettings = /** @class */ (function () {
  93266. function SimplificationSettings(quality, distance, optimizeMesh) {
  93267. this.quality = quality;
  93268. this.distance = distance;
  93269. this.optimizeMesh = optimizeMesh;
  93270. }
  93271. return SimplificationSettings;
  93272. }());
  93273. BABYLON.SimplificationSettings = SimplificationSettings;
  93274. var SimplificationQueue = /** @class */ (function () {
  93275. function SimplificationQueue() {
  93276. this.running = false;
  93277. this._simplificationArray = [];
  93278. }
  93279. SimplificationQueue.prototype.addTask = function (task) {
  93280. this._simplificationArray.push(task);
  93281. };
  93282. SimplificationQueue.prototype.executeNext = function () {
  93283. var task = this._simplificationArray.pop();
  93284. if (task) {
  93285. this.running = true;
  93286. this.runSimplification(task);
  93287. }
  93288. else {
  93289. this.running = false;
  93290. }
  93291. };
  93292. SimplificationQueue.prototype.runSimplification = function (task) {
  93293. var _this = this;
  93294. if (task.parallelProcessing) {
  93295. //parallel simplifier
  93296. task.settings.forEach(function (setting) {
  93297. var simplifier = _this.getSimplifier(task);
  93298. simplifier.simplify(setting, function (newMesh) {
  93299. task.mesh.addLODLevel(setting.distance, newMesh);
  93300. newMesh.isVisible = true;
  93301. //check if it is the last
  93302. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93303. //all done, run the success callback.
  93304. task.successCallback();
  93305. }
  93306. _this.executeNext();
  93307. });
  93308. });
  93309. }
  93310. else {
  93311. //single simplifier.
  93312. var simplifier = this.getSimplifier(task);
  93313. var runDecimation = function (setting, callback) {
  93314. simplifier.simplify(setting, function (newMesh) {
  93315. task.mesh.addLODLevel(setting.distance, newMesh);
  93316. newMesh.isVisible = true;
  93317. //run the next quality level
  93318. callback();
  93319. });
  93320. };
  93321. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93322. runDecimation(task.settings[loop.index], function () {
  93323. loop.executeNext();
  93324. });
  93325. }, function () {
  93326. //execution ended, run the success callback.
  93327. if (task.successCallback) {
  93328. task.successCallback();
  93329. }
  93330. _this.executeNext();
  93331. });
  93332. }
  93333. };
  93334. SimplificationQueue.prototype.getSimplifier = function (task) {
  93335. switch (task.simplificationType) {
  93336. case SimplificationType.QUADRATIC:
  93337. default:
  93338. return new QuadraticErrorSimplification(task.mesh);
  93339. }
  93340. };
  93341. return SimplificationQueue;
  93342. }());
  93343. BABYLON.SimplificationQueue = SimplificationQueue;
  93344. /**
  93345. * The implemented types of simplification
  93346. * At the moment only Quadratic Error Decimation is implemented
  93347. */
  93348. var SimplificationType;
  93349. (function (SimplificationType) {
  93350. /** Quadratic error decimation */
  93351. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93352. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93353. var DecimationTriangle = /** @class */ (function () {
  93354. function DecimationTriangle(vertices) {
  93355. this.vertices = vertices;
  93356. this.error = new Array(4);
  93357. this.deleted = false;
  93358. this.isDirty = false;
  93359. this.deletePending = false;
  93360. this.borderFactor = 0;
  93361. }
  93362. return DecimationTriangle;
  93363. }());
  93364. BABYLON.DecimationTriangle = DecimationTriangle;
  93365. var DecimationVertex = /** @class */ (function () {
  93366. function DecimationVertex(position, id) {
  93367. this.position = position;
  93368. this.id = id;
  93369. this.isBorder = true;
  93370. this.q = new QuadraticMatrix();
  93371. this.triangleCount = 0;
  93372. this.triangleStart = 0;
  93373. this.originalOffsets = [];
  93374. }
  93375. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93376. this.position.copyFrom(newPosition);
  93377. };
  93378. return DecimationVertex;
  93379. }());
  93380. BABYLON.DecimationVertex = DecimationVertex;
  93381. var QuadraticMatrix = /** @class */ (function () {
  93382. function QuadraticMatrix(data) {
  93383. this.data = new Array(10);
  93384. for (var i = 0; i < 10; ++i) {
  93385. if (data && data[i]) {
  93386. this.data[i] = data[i];
  93387. }
  93388. else {
  93389. this.data[i] = 0;
  93390. }
  93391. }
  93392. }
  93393. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93394. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93395. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93396. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93397. return det;
  93398. };
  93399. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93400. for (var i = 0; i < 10; ++i) {
  93401. this.data[i] += matrix.data[i];
  93402. }
  93403. };
  93404. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93405. for (var i = 0; i < 10; ++i) {
  93406. this.data[i] += data[i];
  93407. }
  93408. };
  93409. QuadraticMatrix.prototype.add = function (matrix) {
  93410. var m = new QuadraticMatrix();
  93411. for (var i = 0; i < 10; ++i) {
  93412. m.data[i] = this.data[i] + matrix.data[i];
  93413. }
  93414. return m;
  93415. };
  93416. QuadraticMatrix.FromData = function (a, b, c, d) {
  93417. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93418. };
  93419. //returning an array to avoid garbage collection
  93420. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93421. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93422. };
  93423. return QuadraticMatrix;
  93424. }());
  93425. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93426. var Reference = /** @class */ (function () {
  93427. function Reference(vertexId, triangleId) {
  93428. this.vertexId = vertexId;
  93429. this.triangleId = triangleId;
  93430. }
  93431. return Reference;
  93432. }());
  93433. BABYLON.Reference = Reference;
  93434. /**
  93435. * An implementation of the Quadratic Error simplification algorithm.
  93436. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93437. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93438. * @author RaananW
  93439. */
  93440. var QuadraticErrorSimplification = /** @class */ (function () {
  93441. function QuadraticErrorSimplification(_mesh) {
  93442. this._mesh = _mesh;
  93443. this.syncIterations = 5000;
  93444. this.aggressiveness = 7;
  93445. this.decimationIterations = 100;
  93446. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93447. }
  93448. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93449. var _this = this;
  93450. this.initDecimatedMesh();
  93451. //iterating through the submeshes array, one after the other.
  93452. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93453. _this.initWithMesh(loop.index, function () {
  93454. _this.runDecimation(settings, loop.index, function () {
  93455. loop.executeNext();
  93456. });
  93457. }, settings.optimizeMesh);
  93458. }, function () {
  93459. setTimeout(function () {
  93460. successCallback(_this._reconstructedMesh);
  93461. }, 0);
  93462. });
  93463. };
  93464. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93465. var _this = this;
  93466. var targetCount = ~~(this.triangles.length * settings.quality);
  93467. var deletedTriangles = 0;
  93468. var triangleCount = this.triangles.length;
  93469. var iterationFunction = function (iteration, callback) {
  93470. setTimeout(function () {
  93471. if (iteration % 5 === 0) {
  93472. _this.updateMesh(iteration === 0);
  93473. }
  93474. for (var i = 0; i < _this.triangles.length; ++i) {
  93475. _this.triangles[i].isDirty = false;
  93476. }
  93477. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93478. var trianglesIterator = function (i) {
  93479. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93480. var t = _this.triangles[tIdx];
  93481. if (!t)
  93482. return;
  93483. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93484. return;
  93485. }
  93486. for (var j = 0; j < 3; ++j) {
  93487. if (t.error[j] < threshold) {
  93488. var deleted0 = [];
  93489. var deleted1 = [];
  93490. var v0 = t.vertices[j];
  93491. var v1 = t.vertices[(j + 1) % 3];
  93492. if (v0.isBorder || v1.isBorder)
  93493. continue;
  93494. var p = BABYLON.Vector3.Zero();
  93495. var n = BABYLON.Vector3.Zero();
  93496. var uv = BABYLON.Vector2.Zero();
  93497. var color = new BABYLON.Color4(0, 0, 0, 1);
  93498. _this.calculateError(v0, v1, p, n, uv, color);
  93499. var delTr = new Array();
  93500. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93501. continue;
  93502. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93503. continue;
  93504. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93505. continue;
  93506. var uniqueArray = new Array();
  93507. delTr.forEach(function (deletedT) {
  93508. if (uniqueArray.indexOf(deletedT) === -1) {
  93509. deletedT.deletePending = true;
  93510. uniqueArray.push(deletedT);
  93511. }
  93512. });
  93513. if (uniqueArray.length % 2 !== 0) {
  93514. continue;
  93515. }
  93516. v0.q = v1.q.add(v0.q);
  93517. v0.updatePosition(p);
  93518. var tStart = _this.references.length;
  93519. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93520. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93521. var tCount = _this.references.length - tStart;
  93522. if (tCount <= v0.triangleCount) {
  93523. if (tCount) {
  93524. for (var c = 0; c < tCount; c++) {
  93525. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93526. }
  93527. }
  93528. }
  93529. else {
  93530. v0.triangleStart = tStart;
  93531. }
  93532. v0.triangleCount = tCount;
  93533. break;
  93534. }
  93535. }
  93536. };
  93537. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93538. }, 0);
  93539. };
  93540. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93541. if (triangleCount - deletedTriangles <= targetCount)
  93542. loop.breakLoop();
  93543. else {
  93544. iterationFunction(loop.index, function () {
  93545. loop.executeNext();
  93546. });
  93547. }
  93548. }, function () {
  93549. setTimeout(function () {
  93550. //reconstruct this part of the mesh
  93551. _this.reconstructMesh(submeshIndex);
  93552. successCallback();
  93553. }, 0);
  93554. });
  93555. };
  93556. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93557. var _this = this;
  93558. this.vertices = [];
  93559. this.triangles = [];
  93560. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93561. var indices = this._mesh.getIndices();
  93562. var submesh = this._mesh.subMeshes[submeshIndex];
  93563. var findInVertices = function (positionToSearch) {
  93564. if (optimizeMesh) {
  93565. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93566. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93567. return _this.vertices[ii];
  93568. }
  93569. }
  93570. }
  93571. return null;
  93572. };
  93573. var vertexReferences = [];
  93574. var vertexInit = function (i) {
  93575. if (!positionData) {
  93576. return;
  93577. }
  93578. var offset = i + submesh.verticesStart;
  93579. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93580. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93581. vertex.originalOffsets.push(offset);
  93582. if (vertex.id === _this.vertices.length) {
  93583. _this.vertices.push(vertex);
  93584. }
  93585. vertexReferences.push(vertex.id);
  93586. };
  93587. //var totalVertices = mesh.getTotalVertices();
  93588. var totalVertices = submesh.verticesCount;
  93589. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93590. var indicesInit = function (i) {
  93591. if (!indices) {
  93592. return;
  93593. }
  93594. var offset = (submesh.indexStart / 3) + i;
  93595. var pos = (offset * 3);
  93596. var i0 = indices[pos + 0];
  93597. var i1 = indices[pos + 1];
  93598. var i2 = indices[pos + 2];
  93599. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93600. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93601. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93602. var triangle = new DecimationTriangle([v0, v1, v2]);
  93603. triangle.originalOffset = pos;
  93604. _this.triangles.push(triangle);
  93605. };
  93606. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93607. _this.init(callback);
  93608. });
  93609. });
  93610. };
  93611. QuadraticErrorSimplification.prototype.init = function (callback) {
  93612. var _this = this;
  93613. var triangleInit1 = function (i) {
  93614. var t = _this.triangles[i];
  93615. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93616. for (var j = 0; j < 3; j++) {
  93617. 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))));
  93618. }
  93619. };
  93620. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93621. var triangleInit2 = function (i) {
  93622. var t = _this.triangles[i];
  93623. for (var j = 0; j < 3; ++j) {
  93624. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93625. }
  93626. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93627. };
  93628. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93629. callback();
  93630. });
  93631. });
  93632. };
  93633. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93634. var newTriangles = [];
  93635. var i;
  93636. for (i = 0; i < this.vertices.length; ++i) {
  93637. this.vertices[i].triangleCount = 0;
  93638. }
  93639. var t;
  93640. var j;
  93641. for (i = 0; i < this.triangles.length; ++i) {
  93642. if (!this.triangles[i].deleted) {
  93643. t = this.triangles[i];
  93644. for (j = 0; j < 3; ++j) {
  93645. t.vertices[j].triangleCount = 1;
  93646. }
  93647. newTriangles.push(t);
  93648. }
  93649. }
  93650. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93651. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93652. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93653. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93654. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93655. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93656. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93657. var vertexCount = 0;
  93658. for (i = 0; i < this.vertices.length; ++i) {
  93659. var vertex = this.vertices[i];
  93660. vertex.id = vertexCount;
  93661. if (vertex.triangleCount) {
  93662. vertex.originalOffsets.forEach(function (originalOffset) {
  93663. if (!normalData) {
  93664. return;
  93665. }
  93666. newPositionData.push(vertex.position.x);
  93667. newPositionData.push(vertex.position.y);
  93668. newPositionData.push(vertex.position.z);
  93669. newNormalData.push(normalData[originalOffset * 3]);
  93670. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93671. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93672. if (uvs && uvs.length) {
  93673. newUVsData.push(uvs[(originalOffset * 2)]);
  93674. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93675. }
  93676. else if (colorsData && colorsData.length) {
  93677. newColorsData.push(colorsData[(originalOffset * 4)]);
  93678. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93679. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93680. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93681. }
  93682. ++vertexCount;
  93683. });
  93684. }
  93685. }
  93686. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93687. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93688. var submeshesArray = this._reconstructedMesh.subMeshes;
  93689. this._reconstructedMesh.subMeshes = [];
  93690. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93691. var originalIndices = this._mesh.getIndices();
  93692. for (i = 0; i < newTriangles.length; ++i) {
  93693. t = newTriangles[i]; //now get the new referencing point for each vertex
  93694. [0, 1, 2].forEach(function (idx) {
  93695. var id = originalIndices[t.originalOffset + idx];
  93696. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93697. if (offset < 0)
  93698. offset = 0;
  93699. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93700. });
  93701. }
  93702. //overwriting the old vertex buffers and indices.
  93703. this._reconstructedMesh.setIndices(newIndicesArray);
  93704. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93706. if (newUVsData.length > 0)
  93707. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93708. if (newColorsData.length > 0)
  93709. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93710. //create submesh
  93711. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93712. if (submeshIndex > 0) {
  93713. this._reconstructedMesh.subMeshes = [];
  93714. submeshesArray.forEach(function (submesh) {
  93715. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93716. });
  93717. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93718. }
  93719. };
  93720. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93721. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93722. this._reconstructedMesh.material = this._mesh.material;
  93723. this._reconstructedMesh.parent = this._mesh.parent;
  93724. this._reconstructedMesh.isVisible = false;
  93725. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93726. };
  93727. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93728. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93729. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93730. if (t.deleted)
  93731. continue;
  93732. var s = this.references[vertex1.triangleStart + i].vertexId;
  93733. var v1 = t.vertices[(s + 1) % 3];
  93734. var v2 = t.vertices[(s + 2) % 3];
  93735. if ((v1 === vertex2 || v2 === vertex2)) {
  93736. deletedArray[i] = true;
  93737. delTr.push(t);
  93738. continue;
  93739. }
  93740. var d1 = v1.position.subtract(point);
  93741. d1 = d1.normalize();
  93742. var d2 = v2.position.subtract(point);
  93743. d2 = d2.normalize();
  93744. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93745. return true;
  93746. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93747. deletedArray[i] = false;
  93748. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93749. return true;
  93750. }
  93751. return false;
  93752. };
  93753. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93754. var newDeleted = deletedTriangles;
  93755. for (var i = 0; i < vertex.triangleCount; ++i) {
  93756. var ref = this.references[vertex.triangleStart + i];
  93757. var t = this.triangles[ref.triangleId];
  93758. if (t.deleted)
  93759. continue;
  93760. if (deletedArray[i] && t.deletePending) {
  93761. t.deleted = true;
  93762. newDeleted++;
  93763. continue;
  93764. }
  93765. t.vertices[ref.vertexId] = origVertex;
  93766. t.isDirty = true;
  93767. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93768. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93769. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93770. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93771. this.references.push(ref);
  93772. }
  93773. return newDeleted;
  93774. };
  93775. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93776. for (var i = 0; i < this.vertices.length; ++i) {
  93777. var vCount = [];
  93778. var vId = [];
  93779. var v = this.vertices[i];
  93780. var j;
  93781. for (j = 0; j < v.triangleCount; ++j) {
  93782. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93783. for (var ii = 0; ii < 3; ii++) {
  93784. var ofs = 0;
  93785. var vv = triangle.vertices[ii];
  93786. while (ofs < vCount.length) {
  93787. if (vId[ofs] === vv.id)
  93788. break;
  93789. ++ofs;
  93790. }
  93791. if (ofs === vCount.length) {
  93792. vCount.push(1);
  93793. vId.push(vv.id);
  93794. }
  93795. else {
  93796. vCount[ofs]++;
  93797. }
  93798. }
  93799. }
  93800. for (j = 0; j < vCount.length; ++j) {
  93801. if (vCount[j] === 1) {
  93802. this.vertices[vId[j]].isBorder = true;
  93803. }
  93804. else {
  93805. this.vertices[vId[j]].isBorder = false;
  93806. }
  93807. }
  93808. }
  93809. };
  93810. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93811. if (identifyBorders === void 0) { identifyBorders = false; }
  93812. var i;
  93813. if (!identifyBorders) {
  93814. var newTrianglesVector = [];
  93815. for (i = 0; i < this.triangles.length; ++i) {
  93816. if (!this.triangles[i].deleted) {
  93817. newTrianglesVector.push(this.triangles[i]);
  93818. }
  93819. }
  93820. this.triangles = newTrianglesVector;
  93821. }
  93822. for (i = 0; i < this.vertices.length; ++i) {
  93823. this.vertices[i].triangleCount = 0;
  93824. this.vertices[i].triangleStart = 0;
  93825. }
  93826. var t;
  93827. var j;
  93828. var v;
  93829. for (i = 0; i < this.triangles.length; ++i) {
  93830. t = this.triangles[i];
  93831. for (j = 0; j < 3; ++j) {
  93832. v = t.vertices[j];
  93833. v.triangleCount++;
  93834. }
  93835. }
  93836. var tStart = 0;
  93837. for (i = 0; i < this.vertices.length; ++i) {
  93838. this.vertices[i].triangleStart = tStart;
  93839. tStart += this.vertices[i].triangleCount;
  93840. this.vertices[i].triangleCount = 0;
  93841. }
  93842. var newReferences = new Array(this.triangles.length * 3);
  93843. for (i = 0; i < this.triangles.length; ++i) {
  93844. t = this.triangles[i];
  93845. for (j = 0; j < 3; ++j) {
  93846. v = t.vertices[j];
  93847. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93848. v.triangleCount++;
  93849. }
  93850. }
  93851. this.references = newReferences;
  93852. if (identifyBorders) {
  93853. this.identifyBorder();
  93854. }
  93855. };
  93856. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93857. var x = point.x;
  93858. var y = point.y;
  93859. var z = point.z;
  93860. 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
  93861. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93862. };
  93863. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93864. var q = vertex1.q.add(vertex2.q);
  93865. var border = vertex1.isBorder && vertex2.isBorder;
  93866. var error = 0;
  93867. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93868. if (qDet !== 0 && !border) {
  93869. if (!pointResult) {
  93870. pointResult = BABYLON.Vector3.Zero();
  93871. }
  93872. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93873. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93874. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93875. error = this.vertexError(q, pointResult);
  93876. }
  93877. else {
  93878. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93879. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93880. var error1 = this.vertexError(q, vertex1.position);
  93881. var error2 = this.vertexError(q, vertex2.position);
  93882. var error3 = this.vertexError(q, p3);
  93883. error = Math.min(error1, error2, error3);
  93884. if (error === error1) {
  93885. if (pointResult) {
  93886. pointResult.copyFrom(vertex1.position);
  93887. }
  93888. }
  93889. else if (error === error2) {
  93890. if (pointResult) {
  93891. pointResult.copyFrom(vertex2.position);
  93892. }
  93893. }
  93894. else {
  93895. if (pointResult) {
  93896. pointResult.copyFrom(p3);
  93897. }
  93898. }
  93899. }
  93900. return error;
  93901. };
  93902. return QuadraticErrorSimplification;
  93903. }());
  93904. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93905. })(BABYLON || (BABYLON = {}));
  93906. //# sourceMappingURL=babylon.meshSimplification.js.map
  93907. var BABYLON;
  93908. (function (BABYLON) {
  93909. var MeshLODLevel = /** @class */ (function () {
  93910. function MeshLODLevel(distance, mesh) {
  93911. this.distance = distance;
  93912. this.mesh = mesh;
  93913. }
  93914. return MeshLODLevel;
  93915. }());
  93916. BABYLON.MeshLODLevel = MeshLODLevel;
  93917. })(BABYLON || (BABYLON = {}));
  93918. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93919. var BABYLON;
  93920. (function (BABYLON) {
  93921. /**
  93922. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93923. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93924. */
  93925. var SceneOptimization = /** @class */ (function () {
  93926. /**
  93927. * Creates the SceneOptimization object
  93928. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93929. * @param desc defines the description associated with the optimization
  93930. */
  93931. function SceneOptimization(
  93932. /**
  93933. * Defines the priority of this optimization (0 by default which means first in the list)
  93934. */
  93935. priority) {
  93936. if (priority === void 0) { priority = 0; }
  93937. this.priority = priority;
  93938. }
  93939. /**
  93940. * Gets a string describing the action executed by the current optimization
  93941. * @returns description string
  93942. */
  93943. SceneOptimization.prototype.getDescription = function () {
  93944. return "";
  93945. };
  93946. /**
  93947. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93948. * @param scene defines the current scene where to apply this optimization
  93949. * @param optimizer defines the current optimizer
  93950. * @returns true if everything that can be done was applied
  93951. */
  93952. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93953. return true;
  93954. };
  93955. ;
  93956. return SceneOptimization;
  93957. }());
  93958. BABYLON.SceneOptimization = SceneOptimization;
  93959. /**
  93960. * Defines an optimization used to reduce the size of render target textures
  93961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93962. */
  93963. var TextureOptimization = /** @class */ (function (_super) {
  93964. __extends(TextureOptimization, _super);
  93965. /**
  93966. * Creates the TextureOptimization object
  93967. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93968. * @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
  93969. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93970. */
  93971. function TextureOptimization(
  93972. /**
  93973. * Defines the priority of this optimization (0 by default which means first in the list)
  93974. */
  93975. priority,
  93976. /**
  93977. * 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
  93978. */
  93979. maximumSize,
  93980. /**
  93981. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93982. */
  93983. step) {
  93984. if (priority === void 0) { priority = 0; }
  93985. if (maximumSize === void 0) { maximumSize = 1024; }
  93986. if (step === void 0) { step = 0.5; }
  93987. var _this = _super.call(this, priority) || this;
  93988. _this.priority = priority;
  93989. _this.maximumSize = maximumSize;
  93990. _this.step = step;
  93991. return _this;
  93992. }
  93993. /**
  93994. * Gets a string describing the action executed by the current optimization
  93995. * @returns description string
  93996. */
  93997. TextureOptimization.prototype.getDescription = function () {
  93998. return "Reducing render target texture size to " + this.maximumSize;
  93999. };
  94000. /**
  94001. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94002. * @param scene defines the current scene where to apply this optimization
  94003. * @param optimizer defines the current optimizer
  94004. * @returns true if everything that can be done was applied
  94005. */
  94006. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94007. var allDone = true;
  94008. for (var index = 0; index < scene.textures.length; index++) {
  94009. var texture = scene.textures[index];
  94010. if (!texture.canRescale || texture.getContext) {
  94011. continue;
  94012. }
  94013. var currentSize = texture.getSize();
  94014. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94015. if (maxDimension > this.maximumSize) {
  94016. texture.scale(this.step);
  94017. allDone = false;
  94018. }
  94019. }
  94020. return allDone;
  94021. };
  94022. return TextureOptimization;
  94023. }(SceneOptimization));
  94024. BABYLON.TextureOptimization = TextureOptimization;
  94025. /**
  94026. * Defines an optimization used to increase or decrease the rendering resolution
  94027. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94028. */
  94029. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94030. __extends(HardwareScalingOptimization, _super);
  94031. /**
  94032. * Creates the HardwareScalingOptimization object
  94033. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94034. * @param maximumScale defines the maximum scale to use (2 by default)
  94035. * @param step defines the step to use between two passes (0.5 by default)
  94036. */
  94037. function HardwareScalingOptimization(
  94038. /**
  94039. * Defines the priority of this optimization (0 by default which means first in the list)
  94040. */
  94041. priority,
  94042. /**
  94043. * Defines the maximum scale to use (2 by default)
  94044. */
  94045. maximumScale,
  94046. /**
  94047. * Defines the step to use between two passes (0.5 by default)
  94048. */
  94049. step) {
  94050. if (priority === void 0) { priority = 0; }
  94051. if (maximumScale === void 0) { maximumScale = 2; }
  94052. if (step === void 0) { step = 0.25; }
  94053. var _this = _super.call(this, priority) || this;
  94054. _this.priority = priority;
  94055. _this.maximumScale = maximumScale;
  94056. _this.step = step;
  94057. _this._currentScale = -1;
  94058. _this._directionOffset = 1;
  94059. return _this;
  94060. }
  94061. /**
  94062. * Gets a string describing the action executed by the current optimization
  94063. * @return description string
  94064. */
  94065. HardwareScalingOptimization.prototype.getDescription = function () {
  94066. return "Setting hardware scaling level to " + this._currentScale;
  94067. };
  94068. /**
  94069. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94070. * @param scene defines the current scene where to apply this optimization
  94071. * @param optimizer defines the current optimizer
  94072. * @returns true if everything that can be done was applied
  94073. */
  94074. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94075. if (this._currentScale === -1) {
  94076. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94077. if (this._currentScale > this.maximumScale) {
  94078. this._directionOffset = -1;
  94079. }
  94080. }
  94081. this._currentScale += this._directionOffset * this.step;
  94082. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94083. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94084. };
  94085. ;
  94086. return HardwareScalingOptimization;
  94087. }(SceneOptimization));
  94088. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94089. /**
  94090. * Defines an optimization used to remove shadows
  94091. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94092. */
  94093. var ShadowsOptimization = /** @class */ (function (_super) {
  94094. __extends(ShadowsOptimization, _super);
  94095. function ShadowsOptimization() {
  94096. return _super !== null && _super.apply(this, arguments) || this;
  94097. }
  94098. /**
  94099. * Gets a string describing the action executed by the current optimization
  94100. * @return description string
  94101. */
  94102. ShadowsOptimization.prototype.getDescription = function () {
  94103. return "Turning shadows on/off";
  94104. };
  94105. /**
  94106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94107. * @param scene defines the current scene where to apply this optimization
  94108. * @param optimizer defines the current optimizer
  94109. * @returns true if everything that can be done was applied
  94110. */
  94111. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94112. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94113. return true;
  94114. };
  94115. ;
  94116. return ShadowsOptimization;
  94117. }(SceneOptimization));
  94118. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94119. /**
  94120. * Defines an optimization used to turn post-processes off
  94121. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94122. */
  94123. var PostProcessesOptimization = /** @class */ (function (_super) {
  94124. __extends(PostProcessesOptimization, _super);
  94125. function PostProcessesOptimization() {
  94126. return _super !== null && _super.apply(this, arguments) || this;
  94127. }
  94128. /**
  94129. * Gets a string describing the action executed by the current optimization
  94130. * @return description string
  94131. */
  94132. PostProcessesOptimization.prototype.getDescription = function () {
  94133. return "Turning post-processes on/off";
  94134. };
  94135. /**
  94136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94137. * @param scene defines the current scene where to apply this optimization
  94138. * @param optimizer defines the current optimizer
  94139. * @returns true if everything that can be done was applied
  94140. */
  94141. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94142. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94143. return true;
  94144. };
  94145. ;
  94146. return PostProcessesOptimization;
  94147. }(SceneOptimization));
  94148. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94149. /**
  94150. * Defines an optimization used to turn lens flares off
  94151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94152. */
  94153. var LensFlaresOptimization = /** @class */ (function (_super) {
  94154. __extends(LensFlaresOptimization, _super);
  94155. function LensFlaresOptimization() {
  94156. return _super !== null && _super.apply(this, arguments) || this;
  94157. }
  94158. /**
  94159. * Gets a string describing the action executed by the current optimization
  94160. * @return description string
  94161. */
  94162. LensFlaresOptimization.prototype.getDescription = function () {
  94163. return "Turning lens flares on/off";
  94164. };
  94165. /**
  94166. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94167. * @param scene defines the current scene where to apply this optimization
  94168. * @param optimizer defines the current optimizer
  94169. * @returns true if everything that can be done was applied
  94170. */
  94171. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94172. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94173. return true;
  94174. };
  94175. ;
  94176. return LensFlaresOptimization;
  94177. }(SceneOptimization));
  94178. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94179. /**
  94180. * Defines an optimization based on user defined callback.
  94181. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94182. */
  94183. var CustomOptimization = /** @class */ (function (_super) {
  94184. __extends(CustomOptimization, _super);
  94185. function CustomOptimization() {
  94186. return _super !== null && _super.apply(this, arguments) || this;
  94187. }
  94188. /**
  94189. * Gets a string describing the action executed by the current optimization
  94190. * @returns description string
  94191. */
  94192. CustomOptimization.prototype.getDescription = function () {
  94193. if (this.onGetDescription) {
  94194. return this.onGetDescription();
  94195. }
  94196. return "Running user defined callback";
  94197. };
  94198. /**
  94199. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94200. * @param scene defines the current scene where to apply this optimization
  94201. * @param optimizer defines the current optimizer
  94202. * @returns true if everything that can be done was applied
  94203. */
  94204. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94205. if (this.onApply) {
  94206. return this.onApply(scene, optimizer);
  94207. }
  94208. return true;
  94209. };
  94210. ;
  94211. return CustomOptimization;
  94212. }(SceneOptimization));
  94213. BABYLON.CustomOptimization = CustomOptimization;
  94214. /**
  94215. * Defines an optimization used to turn particles off
  94216. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94217. */
  94218. var ParticlesOptimization = /** @class */ (function (_super) {
  94219. __extends(ParticlesOptimization, _super);
  94220. function ParticlesOptimization() {
  94221. return _super !== null && _super.apply(this, arguments) || this;
  94222. }
  94223. /**
  94224. * Gets a string describing the action executed by the current optimization
  94225. * @return description string
  94226. */
  94227. ParticlesOptimization.prototype.getDescription = function () {
  94228. return "Turning particles on/off";
  94229. };
  94230. /**
  94231. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94232. * @param scene defines the current scene where to apply this optimization
  94233. * @param optimizer defines the current optimizer
  94234. * @returns true if everything that can be done was applied
  94235. */
  94236. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94237. scene.particlesEnabled = optimizer.isInImprovementMode;
  94238. return true;
  94239. };
  94240. ;
  94241. return ParticlesOptimization;
  94242. }(SceneOptimization));
  94243. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94244. /**
  94245. * Defines an optimization used to turn render targets off
  94246. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94247. */
  94248. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94249. __extends(RenderTargetsOptimization, _super);
  94250. function RenderTargetsOptimization() {
  94251. return _super !== null && _super.apply(this, arguments) || this;
  94252. }
  94253. /**
  94254. * Gets a string describing the action executed by the current optimization
  94255. * @return description string
  94256. */
  94257. RenderTargetsOptimization.prototype.getDescription = function () {
  94258. return "Turning render targets off";
  94259. };
  94260. /**
  94261. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94262. * @param scene defines the current scene where to apply this optimization
  94263. * @param optimizer defines the current optimizer
  94264. * @returns true if everything that can be done was applied
  94265. */
  94266. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94267. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94268. return true;
  94269. };
  94270. ;
  94271. return RenderTargetsOptimization;
  94272. }(SceneOptimization));
  94273. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94274. /**
  94275. * Defines an optimization used to merge meshes with compatible materials
  94276. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94277. */
  94278. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94279. __extends(MergeMeshesOptimization, _super);
  94280. function MergeMeshesOptimization() {
  94281. var _this = _super !== null && _super.apply(this, arguments) || this;
  94282. _this._canBeMerged = function (abstractMesh) {
  94283. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94284. return false;
  94285. }
  94286. var mesh = abstractMesh;
  94287. if (!mesh.isVisible || !mesh.isEnabled()) {
  94288. return false;
  94289. }
  94290. if (mesh.instances.length > 0) {
  94291. return false;
  94292. }
  94293. if (mesh.skeleton || mesh.hasLODLevels) {
  94294. return false;
  94295. }
  94296. if (mesh.parent) {
  94297. return false;
  94298. }
  94299. return true;
  94300. };
  94301. return _this;
  94302. }
  94303. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94304. /**
  94305. * Gets or sets a boolean which defines if optimization octree has to be updated
  94306. */
  94307. get: function () {
  94308. return MergeMeshesOptimization._UpdateSelectionTree;
  94309. },
  94310. /**
  94311. * Gets or sets a boolean which defines if optimization octree has to be updated
  94312. */
  94313. set: function (value) {
  94314. MergeMeshesOptimization._UpdateSelectionTree = value;
  94315. },
  94316. enumerable: true,
  94317. configurable: true
  94318. });
  94319. /**
  94320. * Gets a string describing the action executed by the current optimization
  94321. * @return description string
  94322. */
  94323. MergeMeshesOptimization.prototype.getDescription = function () {
  94324. return "Merging similar meshes together";
  94325. };
  94326. /**
  94327. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94328. * @param scene defines the current scene where to apply this optimization
  94329. * @param optimizer defines the current optimizer
  94330. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94331. * @returns true if everything that can be done was applied
  94332. */
  94333. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94334. var globalPool = scene.meshes.slice(0);
  94335. var globalLength = globalPool.length;
  94336. for (var index = 0; index < globalLength; index++) {
  94337. var currentPool = new Array();
  94338. var current = globalPool[index];
  94339. // Checks
  94340. if (!this._canBeMerged(current)) {
  94341. continue;
  94342. }
  94343. currentPool.push(current);
  94344. // Find compatible meshes
  94345. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94346. var otherMesh = globalPool[subIndex];
  94347. if (!this._canBeMerged(otherMesh)) {
  94348. continue;
  94349. }
  94350. if (otherMesh.material !== current.material) {
  94351. continue;
  94352. }
  94353. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94354. continue;
  94355. }
  94356. currentPool.push(otherMesh);
  94357. globalLength--;
  94358. globalPool.splice(subIndex, 1);
  94359. subIndex--;
  94360. }
  94361. if (currentPool.length < 2) {
  94362. continue;
  94363. }
  94364. // Merge meshes
  94365. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94366. }
  94367. if (updateSelectionTree != undefined) {
  94368. if (updateSelectionTree) {
  94369. scene.createOrUpdateSelectionOctree();
  94370. }
  94371. }
  94372. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94373. scene.createOrUpdateSelectionOctree();
  94374. }
  94375. return true;
  94376. };
  94377. ;
  94378. MergeMeshesOptimization._UpdateSelectionTree = false;
  94379. return MergeMeshesOptimization;
  94380. }(SceneOptimization));
  94381. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94382. /**
  94383. * Defines a list of options used by SceneOptimizer
  94384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94385. */
  94386. var SceneOptimizerOptions = /** @class */ (function () {
  94387. /**
  94388. * Creates a new list of options used by SceneOptimizer
  94389. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94390. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94391. */
  94392. function SceneOptimizerOptions(
  94393. /**
  94394. * Defines the target frame rate to reach (60 by default)
  94395. */
  94396. targetFrameRate,
  94397. /**
  94398. * Defines the interval between two checkes (2000ms by default)
  94399. */
  94400. trackerDuration) {
  94401. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94402. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94403. this.targetFrameRate = targetFrameRate;
  94404. this.trackerDuration = trackerDuration;
  94405. /**
  94406. * Gets the list of optimizations to apply
  94407. */
  94408. this.optimizations = new Array();
  94409. }
  94410. /**
  94411. * Add a new optimization
  94412. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94413. * @returns the current SceneOptimizerOptions
  94414. */
  94415. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94416. this.optimizations.push(optimization);
  94417. return this;
  94418. };
  94419. /**
  94420. * Add a new custom optimization
  94421. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94422. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94423. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94424. * @returns the current SceneOptimizerOptions
  94425. */
  94426. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94427. if (priority === void 0) { priority = 0; }
  94428. var optimization = new CustomOptimization(priority);
  94429. optimization.onApply = onApply;
  94430. optimization.onGetDescription = onGetDescription;
  94431. this.optimizations.push(optimization);
  94432. return this;
  94433. };
  94434. /**
  94435. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94436. * @param targetFrameRate defines the target frame rate (60 by default)
  94437. * @returns a SceneOptimizerOptions object
  94438. */
  94439. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94440. var result = new SceneOptimizerOptions(targetFrameRate);
  94441. var priority = 0;
  94442. result.addOptimization(new MergeMeshesOptimization(priority));
  94443. result.addOptimization(new ShadowsOptimization(priority));
  94444. result.addOptimization(new LensFlaresOptimization(priority));
  94445. // Next priority
  94446. priority++;
  94447. result.addOptimization(new PostProcessesOptimization(priority));
  94448. result.addOptimization(new ParticlesOptimization(priority));
  94449. // Next priority
  94450. priority++;
  94451. result.addOptimization(new TextureOptimization(priority, 1024));
  94452. return result;
  94453. };
  94454. /**
  94455. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94456. * @param targetFrameRate defines the target frame rate (60 by default)
  94457. * @returns a SceneOptimizerOptions object
  94458. */
  94459. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94460. var result = new SceneOptimizerOptions(targetFrameRate);
  94461. var priority = 0;
  94462. result.addOptimization(new MergeMeshesOptimization(priority));
  94463. result.addOptimization(new ShadowsOptimization(priority));
  94464. result.addOptimization(new LensFlaresOptimization(priority));
  94465. // Next priority
  94466. priority++;
  94467. result.addOptimization(new PostProcessesOptimization(priority));
  94468. result.addOptimization(new ParticlesOptimization(priority));
  94469. // Next priority
  94470. priority++;
  94471. result.addOptimization(new TextureOptimization(priority, 512));
  94472. // Next priority
  94473. priority++;
  94474. result.addOptimization(new RenderTargetsOptimization(priority));
  94475. // Next priority
  94476. priority++;
  94477. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94478. return result;
  94479. };
  94480. /**
  94481. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94482. * @param targetFrameRate defines the target frame rate (60 by default)
  94483. * @returns a SceneOptimizerOptions object
  94484. */
  94485. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94486. var result = new SceneOptimizerOptions(targetFrameRate);
  94487. var priority = 0;
  94488. result.addOptimization(new MergeMeshesOptimization(priority));
  94489. result.addOptimization(new ShadowsOptimization(priority));
  94490. result.addOptimization(new LensFlaresOptimization(priority));
  94491. // Next priority
  94492. priority++;
  94493. result.addOptimization(new PostProcessesOptimization(priority));
  94494. result.addOptimization(new ParticlesOptimization(priority));
  94495. // Next priority
  94496. priority++;
  94497. result.addOptimization(new TextureOptimization(priority, 256));
  94498. // Next priority
  94499. priority++;
  94500. result.addOptimization(new RenderTargetsOptimization(priority));
  94501. // Next priority
  94502. priority++;
  94503. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94504. return result;
  94505. };
  94506. return SceneOptimizerOptions;
  94507. }());
  94508. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94509. /**
  94510. * Class used to run optimizations in order to reach a target frame rate
  94511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94512. */
  94513. var SceneOptimizer = /** @class */ (function () {
  94514. /**
  94515. * Creates a new SceneOptimizer
  94516. * @param scene defines the scene to work on
  94517. * @param options defines the options to use with the SceneOptimizer
  94518. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94519. * @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)
  94520. */
  94521. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94522. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94523. if (improvementMode === void 0) { improvementMode = false; }
  94524. var _this = this;
  94525. this._isRunning = false;
  94526. this._currentPriorityLevel = 0;
  94527. this._targetFrameRate = 60;
  94528. this._trackerDuration = 2000;
  94529. this._currentFrameRate = 0;
  94530. this._improvementMode = false;
  94531. /**
  94532. * Defines an observable called when the optimizer reaches the target frame rate
  94533. */
  94534. this.onSuccessObservable = new BABYLON.Observable();
  94535. /**
  94536. * Defines an observable called when the optimizer enables an optimization
  94537. */
  94538. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94539. /**
  94540. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94541. */
  94542. this.onFailureObservable = new BABYLON.Observable();
  94543. if (!options) {
  94544. this._options = new SceneOptimizerOptions();
  94545. }
  94546. else {
  94547. this._options = options;
  94548. }
  94549. if (this._options.targetFrameRate) {
  94550. this._targetFrameRate = this._options.targetFrameRate;
  94551. }
  94552. if (this._options.trackerDuration) {
  94553. this._trackerDuration = this._options.trackerDuration;
  94554. }
  94555. if (autoGeneratePriorities) {
  94556. var priority = 0;
  94557. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94558. var optim = _a[_i];
  94559. optim.priority = priority++;
  94560. }
  94561. }
  94562. this._improvementMode = improvementMode;
  94563. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94564. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94565. _this._sceneDisposeObserver = null;
  94566. _this.dispose();
  94567. });
  94568. }
  94569. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94570. /**
  94571. * Gets a boolean indicating if the optimizer is in improvement mode
  94572. */
  94573. get: function () {
  94574. return this._improvementMode;
  94575. },
  94576. enumerable: true,
  94577. configurable: true
  94578. });
  94579. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94580. /**
  94581. * Gets the current priority level (0 at start)
  94582. */
  94583. get: function () {
  94584. return this._currentPriorityLevel;
  94585. },
  94586. enumerable: true,
  94587. configurable: true
  94588. });
  94589. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94590. /**
  94591. * Gets the current frame rate checked by the SceneOptimizer
  94592. */
  94593. get: function () {
  94594. return this._currentFrameRate;
  94595. },
  94596. enumerable: true,
  94597. configurable: true
  94598. });
  94599. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94600. /**
  94601. * Gets or sets the current target frame rate (60 by default)
  94602. */
  94603. get: function () {
  94604. return this._targetFrameRate;
  94605. },
  94606. /**
  94607. * Gets or sets the current target frame rate (60 by default)
  94608. */
  94609. set: function (value) {
  94610. this._targetFrameRate = value;
  94611. },
  94612. enumerable: true,
  94613. configurable: true
  94614. });
  94615. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94616. /**
  94617. * Gets or sets the current interval between two checks (every 2000ms by default)
  94618. */
  94619. get: function () {
  94620. return this._trackerDuration;
  94621. },
  94622. /**
  94623. * Gets or sets the current interval between two checks (every 2000ms by default)
  94624. */
  94625. set: function (value) {
  94626. this._trackerDuration = value;
  94627. },
  94628. enumerable: true,
  94629. configurable: true
  94630. });
  94631. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94632. /**
  94633. * Gets the list of active optimizations
  94634. */
  94635. get: function () {
  94636. return this._options.optimizations;
  94637. },
  94638. enumerable: true,
  94639. configurable: true
  94640. });
  94641. /**
  94642. * Stops the current optimizer
  94643. */
  94644. SceneOptimizer.prototype.stop = function () {
  94645. this._isRunning = false;
  94646. };
  94647. /**
  94648. * Reset the optimizer to initial step (current priority level = 0)
  94649. */
  94650. SceneOptimizer.prototype.reset = function () {
  94651. this._currentPriorityLevel = 0;
  94652. };
  94653. /**
  94654. * Start the optimizer. By default it will try to reach a specific framerate
  94655. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94656. */
  94657. SceneOptimizer.prototype.start = function () {
  94658. var _this = this;
  94659. if (this._isRunning) {
  94660. return;
  94661. }
  94662. this._isRunning = true;
  94663. // Let's wait for the scene to be ready before running our check
  94664. this._scene.executeWhenReady(function () {
  94665. setTimeout(function () {
  94666. _this._checkCurrentState();
  94667. }, _this._trackerDuration);
  94668. });
  94669. };
  94670. SceneOptimizer.prototype._checkCurrentState = function () {
  94671. var _this = this;
  94672. if (!this._isRunning) {
  94673. return;
  94674. }
  94675. var scene = this._scene;
  94676. var options = this._options;
  94677. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94678. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94679. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94680. this._isRunning = false;
  94681. this.onSuccessObservable.notifyObservers(this);
  94682. return;
  94683. }
  94684. // Apply current level of optimizations
  94685. var allDone = true;
  94686. var noOptimizationApplied = true;
  94687. for (var index = 0; index < options.optimizations.length; index++) {
  94688. var optimization = options.optimizations[index];
  94689. if (optimization.priority === this._currentPriorityLevel) {
  94690. noOptimizationApplied = false;
  94691. allDone = allDone && optimization.apply(scene, this);
  94692. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94693. }
  94694. }
  94695. // If no optimization was applied, this is a failure :(
  94696. if (noOptimizationApplied) {
  94697. this._isRunning = false;
  94698. this.onFailureObservable.notifyObservers(this);
  94699. return;
  94700. }
  94701. // If all optimizations were done, move to next level
  94702. if (allDone) {
  94703. this._currentPriorityLevel++;
  94704. }
  94705. // Let's the system running for a specific amount of time before checking FPS
  94706. scene.executeWhenReady(function () {
  94707. setTimeout(function () {
  94708. _this._checkCurrentState();
  94709. }, _this._trackerDuration);
  94710. });
  94711. };
  94712. /**
  94713. * Release all resources
  94714. */
  94715. SceneOptimizer.prototype.dispose = function () {
  94716. this.stop();
  94717. this.onSuccessObservable.clear();
  94718. this.onFailureObservable.clear();
  94719. this.onNewOptimizationAppliedObservable.clear();
  94720. if (this._sceneDisposeObserver) {
  94721. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94722. }
  94723. };
  94724. /**
  94725. * Helper function to create a SceneOptimizer with one single line of code
  94726. * @param scene defines the scene to work on
  94727. * @param options defines the options to use with the SceneOptimizer
  94728. * @param onSuccess defines a callback to call on success
  94729. * @param onFailure defines a callback to call on failure
  94730. * @returns the new SceneOptimizer object
  94731. */
  94732. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94733. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94734. if (onSuccess) {
  94735. optimizer.onSuccessObservable.add(function () {
  94736. onSuccess();
  94737. });
  94738. }
  94739. if (onFailure) {
  94740. optimizer.onFailureObservable.add(function () {
  94741. onFailure();
  94742. });
  94743. }
  94744. optimizer.start();
  94745. return optimizer;
  94746. };
  94747. return SceneOptimizer;
  94748. }());
  94749. BABYLON.SceneOptimizer = SceneOptimizer;
  94750. })(BABYLON || (BABYLON = {}));
  94751. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94752. var BABYLON;
  94753. (function (BABYLON) {
  94754. var OutlineRenderer = /** @class */ (function () {
  94755. function OutlineRenderer(scene) {
  94756. this.zOffset = 1;
  94757. this._scene = scene;
  94758. }
  94759. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94760. var _this = this;
  94761. if (useOverlay === void 0) { useOverlay = false; }
  94762. var scene = this._scene;
  94763. var engine = this._scene.getEngine();
  94764. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94765. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94766. return;
  94767. }
  94768. var mesh = subMesh.getRenderingMesh();
  94769. var material = subMesh.getMaterial();
  94770. if (!material || !scene.activeCamera) {
  94771. return;
  94772. }
  94773. engine.enableEffect(this._effect);
  94774. // Logarithmic depth
  94775. if (material.useLogarithmicDepth) {
  94776. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94777. }
  94778. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94779. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94780. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94781. // Bones
  94782. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94783. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94784. }
  94785. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94786. // Alpha test
  94787. if (material && material.needAlphaTesting()) {
  94788. var alphaTexture = material.getAlphaTestTexture();
  94789. if (alphaTexture) {
  94790. this._effect.setTexture("diffuseSampler", alphaTexture);
  94791. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94792. }
  94793. }
  94794. engine.setZOffset(-this.zOffset);
  94795. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94796. engine.setZOffset(0);
  94797. };
  94798. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94799. var defines = [];
  94800. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94801. var mesh = subMesh.getMesh();
  94802. var material = subMesh.getMaterial();
  94803. if (material) {
  94804. // Alpha test
  94805. if (material.needAlphaTesting()) {
  94806. defines.push("#define ALPHATEST");
  94807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94808. attribs.push(BABYLON.VertexBuffer.UVKind);
  94809. defines.push("#define UV1");
  94810. }
  94811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94813. defines.push("#define UV2");
  94814. }
  94815. }
  94816. //Logarithmic depth
  94817. if (material.useLogarithmicDepth) {
  94818. defines.push("#define LOGARITHMICDEPTH");
  94819. }
  94820. }
  94821. // Bones
  94822. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94823. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94824. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94825. if (mesh.numBoneInfluencers > 4) {
  94826. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94827. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94828. }
  94829. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94830. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94831. }
  94832. else {
  94833. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94834. }
  94835. // Instances
  94836. if (useInstances) {
  94837. defines.push("#define INSTANCES");
  94838. attribs.push("world0");
  94839. attribs.push("world1");
  94840. attribs.push("world2");
  94841. attribs.push("world3");
  94842. }
  94843. // Get correct effect
  94844. var join = defines.join("\n");
  94845. if (this._cachedDefines !== join) {
  94846. this._cachedDefines = join;
  94847. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94848. }
  94849. return this._effect.isReady();
  94850. };
  94851. return OutlineRenderer;
  94852. }());
  94853. BABYLON.OutlineRenderer = OutlineRenderer;
  94854. })(BABYLON || (BABYLON = {}));
  94855. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94856. var BABYLON;
  94857. (function (BABYLON) {
  94858. var FaceAdjacencies = /** @class */ (function () {
  94859. function FaceAdjacencies() {
  94860. this.edges = new Array();
  94861. this.edgesConnectedCount = 0;
  94862. }
  94863. return FaceAdjacencies;
  94864. }());
  94865. var EdgesRenderer = /** @class */ (function () {
  94866. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94867. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94868. if (epsilon === void 0) { epsilon = 0.95; }
  94869. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94870. this.edgesWidthScalerForOrthographic = 1000.0;
  94871. this.edgesWidthScalerForPerspective = 50.0;
  94872. this._linesPositions = new Array();
  94873. this._linesNormals = new Array();
  94874. this._linesIndices = new Array();
  94875. this._buffers = {};
  94876. this._checkVerticesInsteadOfIndices = false;
  94877. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94878. this.isEnabled = true;
  94879. this._source = source;
  94880. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94881. this._epsilon = epsilon;
  94882. this._prepareRessources();
  94883. this._generateEdgesLines();
  94884. }
  94885. EdgesRenderer.prototype._prepareRessources = function () {
  94886. if (this._lineShader) {
  94887. return;
  94888. }
  94889. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94890. attributes: ["position", "normal"],
  94891. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94892. });
  94893. this._lineShader.disableDepthWrite = true;
  94894. this._lineShader.backFaceCulling = false;
  94895. };
  94896. EdgesRenderer.prototype._rebuild = function () {
  94897. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94898. if (buffer) {
  94899. buffer._rebuild();
  94900. }
  94901. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94902. if (buffer) {
  94903. buffer._rebuild();
  94904. }
  94905. var scene = this._source.getScene();
  94906. var engine = scene.getEngine();
  94907. this._ib = engine.createIndexBuffer(this._linesIndices);
  94908. };
  94909. EdgesRenderer.prototype.dispose = function () {
  94910. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94911. if (buffer) {
  94912. buffer.dispose();
  94913. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94914. }
  94915. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94916. if (buffer) {
  94917. buffer.dispose();
  94918. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94919. }
  94920. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94921. this._lineShader.dispose();
  94922. };
  94923. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94924. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94925. return 0;
  94926. }
  94927. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94928. return 1;
  94929. }
  94930. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94931. return 2;
  94932. }
  94933. return -1;
  94934. };
  94935. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94936. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94937. return 0;
  94938. }
  94939. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94940. return 1;
  94941. }
  94942. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94943. return 2;
  94944. }
  94945. return -1;
  94946. };
  94947. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94948. var needToCreateLine;
  94949. if (edge === undefined) {
  94950. needToCreateLine = true;
  94951. }
  94952. else {
  94953. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94954. needToCreateLine = dotProduct < this._epsilon;
  94955. }
  94956. if (needToCreateLine) {
  94957. var offset = this._linesPositions.length / 3;
  94958. var normal = p0.subtract(p1);
  94959. normal.normalize();
  94960. // Positions
  94961. this._linesPositions.push(p0.x);
  94962. this._linesPositions.push(p0.y);
  94963. this._linesPositions.push(p0.z);
  94964. this._linesPositions.push(p0.x);
  94965. this._linesPositions.push(p0.y);
  94966. this._linesPositions.push(p0.z);
  94967. this._linesPositions.push(p1.x);
  94968. this._linesPositions.push(p1.y);
  94969. this._linesPositions.push(p1.z);
  94970. this._linesPositions.push(p1.x);
  94971. this._linesPositions.push(p1.y);
  94972. this._linesPositions.push(p1.z);
  94973. // Normals
  94974. this._linesNormals.push(p1.x);
  94975. this._linesNormals.push(p1.y);
  94976. this._linesNormals.push(p1.z);
  94977. this._linesNormals.push(-1);
  94978. this._linesNormals.push(p1.x);
  94979. this._linesNormals.push(p1.y);
  94980. this._linesNormals.push(p1.z);
  94981. this._linesNormals.push(1);
  94982. this._linesNormals.push(p0.x);
  94983. this._linesNormals.push(p0.y);
  94984. this._linesNormals.push(p0.z);
  94985. this._linesNormals.push(-1);
  94986. this._linesNormals.push(p0.x);
  94987. this._linesNormals.push(p0.y);
  94988. this._linesNormals.push(p0.z);
  94989. this._linesNormals.push(1);
  94990. // Indices
  94991. this._linesIndices.push(offset);
  94992. this._linesIndices.push(offset + 1);
  94993. this._linesIndices.push(offset + 2);
  94994. this._linesIndices.push(offset);
  94995. this._linesIndices.push(offset + 2);
  94996. this._linesIndices.push(offset + 3);
  94997. }
  94998. };
  94999. EdgesRenderer.prototype._generateEdgesLines = function () {
  95000. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95001. var indices = this._source.getIndices();
  95002. if (!indices || !positions) {
  95003. return;
  95004. }
  95005. // First let's find adjacencies
  95006. var adjacencies = new Array();
  95007. var faceNormals = new Array();
  95008. var index;
  95009. var faceAdjacencies;
  95010. // Prepare faces
  95011. for (index = 0; index < indices.length; index += 3) {
  95012. faceAdjacencies = new FaceAdjacencies();
  95013. var p0Index = indices[index];
  95014. var p1Index = indices[index + 1];
  95015. var p2Index = indices[index + 2];
  95016. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95017. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95018. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95019. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95020. faceNormal.normalize();
  95021. faceNormals.push(faceNormal);
  95022. adjacencies.push(faceAdjacencies);
  95023. }
  95024. // Scan
  95025. for (index = 0; index < adjacencies.length; index++) {
  95026. faceAdjacencies = adjacencies[index];
  95027. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95028. var otherFaceAdjacencies = adjacencies[otherIndex];
  95029. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95030. break;
  95031. }
  95032. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95033. continue;
  95034. }
  95035. var otherP0 = indices[otherIndex * 3];
  95036. var otherP1 = indices[otherIndex * 3 + 1];
  95037. var otherP2 = indices[otherIndex * 3 + 2];
  95038. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95039. var otherEdgeIndex = 0;
  95040. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95041. continue;
  95042. }
  95043. switch (edgeIndex) {
  95044. case 0:
  95045. if (this._checkVerticesInsteadOfIndices) {
  95046. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95047. }
  95048. else {
  95049. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95050. }
  95051. break;
  95052. case 1:
  95053. if (this._checkVerticesInsteadOfIndices) {
  95054. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95055. }
  95056. else {
  95057. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95058. }
  95059. break;
  95060. case 2:
  95061. if (this._checkVerticesInsteadOfIndices) {
  95062. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95063. }
  95064. else {
  95065. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95066. }
  95067. break;
  95068. }
  95069. if (otherEdgeIndex === -1) {
  95070. continue;
  95071. }
  95072. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95073. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95074. faceAdjacencies.edgesConnectedCount++;
  95075. otherFaceAdjacencies.edgesConnectedCount++;
  95076. if (faceAdjacencies.edgesConnectedCount === 3) {
  95077. break;
  95078. }
  95079. }
  95080. }
  95081. }
  95082. // Create lines
  95083. for (index = 0; index < adjacencies.length; index++) {
  95084. // 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
  95085. var current = adjacencies[index];
  95086. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95087. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95088. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95089. }
  95090. // Merge into a single mesh
  95091. var engine = this._source.getScene().getEngine();
  95092. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95093. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95094. this._ib = engine.createIndexBuffer(this._linesIndices);
  95095. this._indicesCount = this._linesIndices.length;
  95096. };
  95097. EdgesRenderer.prototype.render = function () {
  95098. var scene = this._source.getScene();
  95099. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95100. return;
  95101. }
  95102. var engine = scene.getEngine();
  95103. this._lineShader._preBind();
  95104. // VBOs
  95105. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95106. scene.resetCachedMaterial();
  95107. this._lineShader.setColor4("color", this._source.edgesColor);
  95108. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95109. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95110. }
  95111. else {
  95112. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95113. }
  95114. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95115. this._lineShader.bind(this._source.getWorldMatrix());
  95116. // Draw order
  95117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95118. this._lineShader.unbind();
  95119. engine.setDepthWrite(true);
  95120. };
  95121. return EdgesRenderer;
  95122. }());
  95123. BABYLON.EdgesRenderer = EdgesRenderer;
  95124. })(BABYLON || (BABYLON = {}));
  95125. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95126. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95127. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95128. s = arguments[i];
  95129. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95130. t[p] = s[p];
  95131. }
  95132. return t;
  95133. };
  95134. var BABYLON;
  95135. (function (BABYLON) {
  95136. /**
  95137. * The effect layer Helps adding post process effect blended with the main pass.
  95138. *
  95139. * This can be for instance use to generate glow or higlight effects on the scene.
  95140. *
  95141. * The effect layer class can not be used directly and is intented to inherited from to be
  95142. * customized per effects.
  95143. */
  95144. var EffectLayer = /** @class */ (function () {
  95145. /**
  95146. * Instantiates a new effect Layer and references it in the scene.
  95147. * @param name The name of the layer
  95148. * @param scene The scene to use the layer in
  95149. */
  95150. function EffectLayer(
  95151. /** The Friendly of the effect in the scene */
  95152. name, scene) {
  95153. this._vertexBuffers = {};
  95154. this._maxSize = 0;
  95155. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95156. this._shouldRender = true;
  95157. this._postProcesses = [];
  95158. this._textures = [];
  95159. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95160. /**
  95161. * The clear color of the texture used to generate the glow map.
  95162. */
  95163. this.neutralColor = new BABYLON.Color4();
  95164. /**
  95165. * Specifies wether the highlight layer is enabled or not.
  95166. */
  95167. this.isEnabled = true;
  95168. /**
  95169. * An event triggered when the effect layer has been disposed.
  95170. */
  95171. this.onDisposeObservable = new BABYLON.Observable();
  95172. /**
  95173. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95174. */
  95175. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95176. /**
  95177. * An event triggered when the generated texture is being merged in the scene.
  95178. */
  95179. this.onBeforeComposeObservable = new BABYLON.Observable();
  95180. /**
  95181. * An event triggered when the generated texture has been merged in the scene.
  95182. */
  95183. this.onAfterComposeObservable = new BABYLON.Observable();
  95184. /**
  95185. * An event triggered when the efffect layer changes its size.
  95186. */
  95187. this.onSizeChangedObservable = new BABYLON.Observable();
  95188. this.name = name;
  95189. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95190. this._engine = scene.getEngine();
  95191. this._maxSize = this._engine.getCaps().maxTextureSize;
  95192. this._scene.effectLayers.push(this);
  95193. // Generate Buffers
  95194. this._generateIndexBuffer();
  95195. this._genrateVertexBuffer();
  95196. }
  95197. Object.defineProperty(EffectLayer.prototype, "camera", {
  95198. /**
  95199. * Gets the camera attached to the layer.
  95200. */
  95201. get: function () {
  95202. return this._effectLayerOptions.camera;
  95203. },
  95204. enumerable: true,
  95205. configurable: true
  95206. });
  95207. /**
  95208. * Initializes the effect layer with the required options.
  95209. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95210. */
  95211. EffectLayer.prototype._init = function (options) {
  95212. // Adapt options
  95213. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95214. this._setMainTextureSize();
  95215. this._createMainTexture();
  95216. this._createTextureAndPostProcesses();
  95217. this._mergeEffect = this._createMergeEffect();
  95218. };
  95219. /**
  95220. * Generates the index buffer of the full screen quad blending to the main canvas.
  95221. */
  95222. EffectLayer.prototype._generateIndexBuffer = function () {
  95223. // Indices
  95224. var indices = [];
  95225. indices.push(0);
  95226. indices.push(1);
  95227. indices.push(2);
  95228. indices.push(0);
  95229. indices.push(2);
  95230. indices.push(3);
  95231. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95232. };
  95233. /**
  95234. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95235. */
  95236. EffectLayer.prototype._genrateVertexBuffer = function () {
  95237. // VBO
  95238. var vertices = [];
  95239. vertices.push(1, 1);
  95240. vertices.push(-1, 1);
  95241. vertices.push(-1, -1);
  95242. vertices.push(1, -1);
  95243. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95244. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95245. };
  95246. /**
  95247. * Sets the main texture desired size which is the closest power of two
  95248. * of the engine canvas size.
  95249. */
  95250. EffectLayer.prototype._setMainTextureSize = function () {
  95251. if (this._effectLayerOptions.mainTextureFixedSize) {
  95252. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95253. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95254. }
  95255. else {
  95256. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95257. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95258. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95259. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95260. }
  95261. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95262. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95263. };
  95264. /**
  95265. * Creates the main texture for the effect layer.
  95266. */
  95267. EffectLayer.prototype._createMainTexture = function () {
  95268. var _this = this;
  95269. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95270. width: this._mainTextureDesiredSize.width,
  95271. height: this._mainTextureDesiredSize.height
  95272. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95273. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95274. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95275. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95276. this._mainTexture.anisotropicFilteringLevel = 1;
  95277. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95278. this._mainTexture.renderParticles = false;
  95279. this._mainTexture.renderList = null;
  95280. this._mainTexture.ignoreCameraViewport = true;
  95281. // Custom render function
  95282. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95283. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95284. var index;
  95285. var engine = _this._scene.getEngine();
  95286. if (depthOnlySubMeshes.length) {
  95287. engine.setColorWrite(false);
  95288. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95289. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95290. }
  95291. engine.setColorWrite(true);
  95292. }
  95293. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95294. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95295. }
  95296. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95297. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95298. }
  95299. for (index = 0; index < transparentSubMeshes.length; index++) {
  95300. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95301. }
  95302. };
  95303. this._mainTexture.onClearObservable.add(function (engine) {
  95304. engine.clear(_this.neutralColor, true, true, true);
  95305. });
  95306. };
  95307. /**
  95308. * Checks for the readiness of the element composing the layer.
  95309. * @param subMesh the mesh to check for
  95310. * @param useInstances specify wether or not to use instances to render the mesh
  95311. * @param emissiveTexture the associated emissive texture used to generate the glow
  95312. * @return true if ready otherwise, false
  95313. */
  95314. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95315. var material = subMesh.getMaterial();
  95316. if (!material) {
  95317. return false;
  95318. }
  95319. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95320. return false;
  95321. }
  95322. var defines = [];
  95323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95324. var mesh = subMesh.getMesh();
  95325. var uv1 = false;
  95326. var uv2 = false;
  95327. // Alpha test
  95328. if (material && material.needAlphaTesting()) {
  95329. var alphaTexture = material.getAlphaTestTexture();
  95330. if (alphaTexture) {
  95331. defines.push("#define ALPHATEST");
  95332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95333. alphaTexture.coordinatesIndex === 1) {
  95334. defines.push("#define DIFFUSEUV2");
  95335. uv2 = true;
  95336. }
  95337. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95338. defines.push("#define DIFFUSEUV1");
  95339. uv1 = true;
  95340. }
  95341. }
  95342. }
  95343. // Emissive
  95344. if (emissiveTexture) {
  95345. defines.push("#define EMISSIVE");
  95346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95347. emissiveTexture.coordinatesIndex === 1) {
  95348. defines.push("#define EMISSIVEUV2");
  95349. uv2 = true;
  95350. }
  95351. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95352. defines.push("#define EMISSIVEUV1");
  95353. uv1 = true;
  95354. }
  95355. }
  95356. if (uv1) {
  95357. attribs.push(BABYLON.VertexBuffer.UVKind);
  95358. defines.push("#define UV1");
  95359. }
  95360. if (uv2) {
  95361. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95362. defines.push("#define UV2");
  95363. }
  95364. // Bones
  95365. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95368. if (mesh.numBoneInfluencers > 4) {
  95369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95371. }
  95372. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95373. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95374. }
  95375. else {
  95376. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95377. }
  95378. // Morph targets
  95379. var manager = mesh.morphTargetManager;
  95380. var morphInfluencers = 0;
  95381. if (manager) {
  95382. if (manager.numInfluencers > 0) {
  95383. defines.push("#define MORPHTARGETS");
  95384. morphInfluencers = manager.numInfluencers;
  95385. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95386. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95387. }
  95388. }
  95389. // Instances
  95390. if (useInstances) {
  95391. defines.push("#define INSTANCES");
  95392. attribs.push("world0");
  95393. attribs.push("world1");
  95394. attribs.push("world2");
  95395. attribs.push("world3");
  95396. }
  95397. // Get correct effect
  95398. var join = defines.join("\n");
  95399. if (this._cachedDefines !== join) {
  95400. this._cachedDefines = join;
  95401. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95402. }
  95403. return this._effectLayerMapGenerationEffect.isReady();
  95404. };
  95405. /**
  95406. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95407. */
  95408. EffectLayer.prototype.render = function () {
  95409. var currentEffect = this._mergeEffect;
  95410. // Check
  95411. if (!currentEffect.isReady())
  95412. return;
  95413. for (var i = 0; i < this._postProcesses.length; i++) {
  95414. if (!this._postProcesses[i].isReady()) {
  95415. return;
  95416. }
  95417. }
  95418. var engine = this._scene.getEngine();
  95419. this.onBeforeComposeObservable.notifyObservers(this);
  95420. // Render
  95421. engine.enableEffect(currentEffect);
  95422. engine.setState(false);
  95423. // VBOs
  95424. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95425. // Cache
  95426. var previousAlphaMode = engine.getAlphaMode();
  95427. // Go Blend.
  95428. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95429. // Blends the map on the main canvas.
  95430. this._internalRender(currentEffect);
  95431. // Restore Alpha
  95432. engine.setAlphaMode(previousAlphaMode);
  95433. this.onAfterComposeObservable.notifyObservers(this);
  95434. // Handle size changes.
  95435. var size = this._mainTexture.getSize();
  95436. this._setMainTextureSize();
  95437. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95438. // Recreate RTT and post processes on size change.
  95439. this.onSizeChangedObservable.notifyObservers(this);
  95440. this._disposeTextureAndPostProcesses();
  95441. this._createMainTexture();
  95442. this._createTextureAndPostProcesses();
  95443. }
  95444. };
  95445. /**
  95446. * Determine if a given mesh will be used in the current effect.
  95447. * @param mesh mesh to test
  95448. * @returns true if the mesh will be used
  95449. */
  95450. EffectLayer.prototype.hasMesh = function (mesh) {
  95451. return true;
  95452. };
  95453. /**
  95454. * Returns true if the layer contains information to display, otherwise false.
  95455. * @returns true if the glow layer should be rendered
  95456. */
  95457. EffectLayer.prototype.shouldRender = function () {
  95458. return this.isEnabled && this._shouldRender;
  95459. };
  95460. /**
  95461. * Returns true if the mesh should render, otherwise false.
  95462. * @param mesh The mesh to render
  95463. * @returns true if it should render otherwise false
  95464. */
  95465. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95466. return true;
  95467. };
  95468. /**
  95469. * Returns true if the mesh should render, otherwise false.
  95470. * @param mesh The mesh to render
  95471. * @returns true if it should render otherwise false
  95472. */
  95473. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95474. return true;
  95475. };
  95476. /**
  95477. * Renders the submesh passed in parameter to the generation map.
  95478. */
  95479. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95480. var _this = this;
  95481. if (!this.shouldRender()) {
  95482. return;
  95483. }
  95484. var material = subMesh.getMaterial();
  95485. var mesh = subMesh.getRenderingMesh();
  95486. var scene = this._scene;
  95487. var engine = scene.getEngine();
  95488. if (!material) {
  95489. return;
  95490. }
  95491. // Do not block in blend mode.
  95492. if (material.needAlphaBlendingForMesh(mesh)) {
  95493. return;
  95494. }
  95495. // Culling
  95496. engine.setState(material.backFaceCulling);
  95497. // Managing instances
  95498. var batch = mesh._getInstancesRenderList(subMesh._id);
  95499. if (batch.mustReturn) {
  95500. return;
  95501. }
  95502. // Early Exit per mesh
  95503. if (!this._shouldRenderMesh(mesh)) {
  95504. return;
  95505. }
  95506. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95507. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95508. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95509. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95510. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95511. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95512. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95513. // Alpha test
  95514. if (material && material.needAlphaTesting()) {
  95515. var alphaTexture = material.getAlphaTestTexture();
  95516. if (alphaTexture) {
  95517. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95518. var textureMatrix = alphaTexture.getTextureMatrix();
  95519. if (textureMatrix) {
  95520. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95521. }
  95522. }
  95523. }
  95524. // Glow emissive only
  95525. if (this._emissiveTextureAndColor.texture) {
  95526. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95527. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95528. }
  95529. // Bones
  95530. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95531. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95532. }
  95533. // Morph targets
  95534. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95535. // Draw
  95536. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95537. }
  95538. else {
  95539. // Need to reset refresh rate of the shadowMap
  95540. this._mainTexture.resetRefreshCounter();
  95541. }
  95542. };
  95543. /**
  95544. * Rebuild the required buffers.
  95545. * @hidden Internal use only.
  95546. */
  95547. EffectLayer.prototype._rebuild = function () {
  95548. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95549. if (vb) {
  95550. vb._rebuild();
  95551. }
  95552. this._generateIndexBuffer();
  95553. };
  95554. /**
  95555. * Dispose only the render target textures and post process.
  95556. */
  95557. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95558. this._mainTexture.dispose();
  95559. for (var i = 0; i < this._postProcesses.length; i++) {
  95560. if (this._postProcesses[i]) {
  95561. this._postProcesses[i].dispose();
  95562. }
  95563. }
  95564. this._postProcesses = [];
  95565. for (var i = 0; i < this._textures.length; i++) {
  95566. if (this._textures[i]) {
  95567. this._textures[i].dispose();
  95568. }
  95569. }
  95570. this._textures = [];
  95571. };
  95572. /**
  95573. * Dispose the highlight layer and free resources.
  95574. */
  95575. EffectLayer.prototype.dispose = function () {
  95576. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95577. if (vertexBuffer) {
  95578. vertexBuffer.dispose();
  95579. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95580. }
  95581. if (this._indexBuffer) {
  95582. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95583. this._indexBuffer = null;
  95584. }
  95585. // Clean textures and post processes
  95586. this._disposeTextureAndPostProcesses();
  95587. // Remove from scene
  95588. var index = this._scene.effectLayers.indexOf(this, 0);
  95589. if (index > -1) {
  95590. this._scene.effectLayers.splice(index, 1);
  95591. }
  95592. // Callback
  95593. this.onDisposeObservable.notifyObservers(this);
  95594. this.onDisposeObservable.clear();
  95595. this.onBeforeRenderMainTextureObservable.clear();
  95596. this.onBeforeComposeObservable.clear();
  95597. this.onAfterComposeObservable.clear();
  95598. this.onSizeChangedObservable.clear();
  95599. };
  95600. /**
  95601. * Gets the class name of the effect layer
  95602. * @returns the string with the class name of the effect layer
  95603. */
  95604. EffectLayer.prototype.getClassName = function () {
  95605. return "EffectLayer";
  95606. };
  95607. /**
  95608. * Creates an effect layer from parsed effect layer data
  95609. * @param parsedEffectLayer defines effect layer data
  95610. * @param scene defines the current scene
  95611. * @param rootUrl defines the root URL containing the effect layer information
  95612. * @returns a parsed effect Layer
  95613. */
  95614. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95615. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95616. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95617. };
  95618. __decorate([
  95619. BABYLON.serialize()
  95620. ], EffectLayer.prototype, "name", void 0);
  95621. __decorate([
  95622. BABYLON.serializeAsColor4()
  95623. ], EffectLayer.prototype, "neutralColor", void 0);
  95624. __decorate([
  95625. BABYLON.serialize()
  95626. ], EffectLayer.prototype, "isEnabled", void 0);
  95627. __decorate([
  95628. BABYLON.serializeAsCameraReference()
  95629. ], EffectLayer.prototype, "camera", null);
  95630. return EffectLayer;
  95631. }());
  95632. BABYLON.EffectLayer = EffectLayer;
  95633. })(BABYLON || (BABYLON = {}));
  95634. //# sourceMappingURL=babylon.effectLayer.js.map
  95635. var BABYLON;
  95636. (function (BABYLON) {
  95637. /**
  95638. * Special Glow Blur post process only blurring the alpha channel
  95639. * It enforces keeping the most luminous color in the color channel.
  95640. */
  95641. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95642. __extends(GlowBlurPostProcess, _super);
  95643. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95645. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95646. _this.direction = direction;
  95647. _this.kernel = kernel;
  95648. _this.onApplyObservable.add(function (effect) {
  95649. effect.setFloat2("screenSize", _this.width, _this.height);
  95650. effect.setVector2("direction", _this.direction);
  95651. effect.setFloat("blurWidth", _this.kernel);
  95652. });
  95653. return _this;
  95654. }
  95655. return GlowBlurPostProcess;
  95656. }(BABYLON.PostProcess));
  95657. /**
  95658. * The highlight layer Helps adding a glow effect around a mesh.
  95659. *
  95660. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95661. * glowy meshes to your scene.
  95662. *
  95663. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95664. */
  95665. var HighlightLayer = /** @class */ (function (_super) {
  95666. __extends(HighlightLayer, _super);
  95667. /**
  95668. * Instantiates a new highlight Layer and references it to the scene..
  95669. * @param name The name of the layer
  95670. * @param scene The scene to use the layer in
  95671. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95672. */
  95673. function HighlightLayer(name, scene, options) {
  95674. var _this = _super.call(this, name, scene) || this;
  95675. _this.name = name;
  95676. /**
  95677. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95678. */
  95679. _this.innerGlow = true;
  95680. /**
  95681. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95682. */
  95683. _this.outerGlow = true;
  95684. /**
  95685. * An event triggered when the highlight layer is being blurred.
  95686. */
  95687. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95688. /**
  95689. * An event triggered when the highlight layer has been blurred.
  95690. */
  95691. _this.onAfterBlurObservable = new BABYLON.Observable();
  95692. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95693. _this._meshes = {};
  95694. _this._excludedMeshes = {};
  95695. _this.neutralColor = HighlightLayer.NeutralColor;
  95696. // Warn on stencil
  95697. if (!_this._engine.isStencilEnable) {
  95698. 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 }");
  95699. }
  95700. // Adapt options
  95701. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95702. // Initialize the layer
  95703. _this._init({
  95704. alphaBlendingMode: _this._options.alphaBlendingMode,
  95705. camera: _this._options.camera,
  95706. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95707. mainTextureRatio: _this._options.mainTextureRatio
  95708. });
  95709. // Do not render as long as no meshes have been added
  95710. _this._shouldRender = false;
  95711. return _this;
  95712. }
  95713. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95714. /**
  95715. * Gets the horizontal size of the blur.
  95716. */
  95717. get: function () {
  95718. return this._horizontalBlurPostprocess.kernel;
  95719. },
  95720. /**
  95721. * Specifies the horizontal size of the blur.
  95722. */
  95723. set: function (value) {
  95724. this._horizontalBlurPostprocess.kernel = value;
  95725. },
  95726. enumerable: true,
  95727. configurable: true
  95728. });
  95729. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95730. /**
  95731. * Gets the vertical size of the blur.
  95732. */
  95733. get: function () {
  95734. return this._verticalBlurPostprocess.kernel;
  95735. },
  95736. /**
  95737. * Specifies the vertical size of the blur.
  95738. */
  95739. set: function (value) {
  95740. this._verticalBlurPostprocess.kernel = value;
  95741. },
  95742. enumerable: true,
  95743. configurable: true
  95744. });
  95745. /**
  95746. * Get the effect name of the layer.
  95747. * @return The effect name
  95748. */
  95749. HighlightLayer.prototype.getEffectName = function () {
  95750. return HighlightLayer.EffectName;
  95751. };
  95752. /**
  95753. * Create the merge effect. This is the shader use to blit the information back
  95754. * to the main canvas at the end of the scene rendering.
  95755. */
  95756. HighlightLayer.prototype._createMergeEffect = function () {
  95757. // Effect
  95758. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95759. };
  95760. /**
  95761. * Creates the render target textures and post processes used in the highlight layer.
  95762. */
  95763. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95764. var _this = this;
  95765. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95766. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95767. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95768. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95769. var textureType = 0;
  95770. if (this._engine.getCaps().textureHalfFloatRender) {
  95771. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95772. }
  95773. else {
  95774. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95775. }
  95776. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95777. width: blurTextureWidth,
  95778. height: blurTextureHeight
  95779. }, this._scene, false, true, textureType);
  95780. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95781. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95782. this._blurTexture.anisotropicFilteringLevel = 16;
  95783. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95784. this._blurTexture.renderParticles = false;
  95785. this._blurTexture.ignoreCameraViewport = true;
  95786. this._textures = [this._blurTexture];
  95787. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95788. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95789. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95790. effect.setTexture("textureSampler", _this._mainTexture);
  95791. });
  95792. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95793. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95794. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95795. });
  95796. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95797. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95798. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95799. });
  95800. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95801. }
  95802. else {
  95803. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95804. width: blurTextureWidth,
  95805. height: blurTextureHeight
  95806. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95807. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95808. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95809. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95810. effect.setTexture("textureSampler", _this._mainTexture);
  95811. });
  95812. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95813. width: blurTextureWidth,
  95814. height: blurTextureHeight
  95815. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95816. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95817. }
  95818. this._mainTexture.onAfterUnbindObservable.add(function () {
  95819. _this.onBeforeBlurObservable.notifyObservers(_this);
  95820. var internalTexture = _this._blurTexture.getInternalTexture();
  95821. if (internalTexture) {
  95822. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95823. }
  95824. _this.onAfterBlurObservable.notifyObservers(_this);
  95825. });
  95826. // Prevent autoClear.
  95827. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95828. };
  95829. /**
  95830. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95831. */
  95832. HighlightLayer.prototype.needStencil = function () {
  95833. return true;
  95834. };
  95835. /**
  95836. * Checks for the readiness of the element composing the layer.
  95837. * @param subMesh the mesh to check for
  95838. * @param useInstances specify wether or not to use instances to render the mesh
  95839. * @param emissiveTexture the associated emissive texture used to generate the glow
  95840. * @return true if ready otherwise, false
  95841. */
  95842. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95843. var material = subMesh.getMaterial();
  95844. var mesh = subMesh.getRenderingMesh();
  95845. if (!material || !mesh || !this._meshes) {
  95846. return false;
  95847. }
  95848. var emissiveTexture = null;
  95849. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95850. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95851. emissiveTexture = material.emissiveTexture;
  95852. }
  95853. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95854. };
  95855. /**
  95856. * Implementation specific of rendering the generating effect on the main canvas.
  95857. * @param effect The effect used to render through
  95858. */
  95859. HighlightLayer.prototype._internalRender = function (effect) {
  95860. // Texture
  95861. effect.setTexture("textureSampler", this._blurTexture);
  95862. // Cache
  95863. var engine = this._engine;
  95864. var previousStencilBuffer = engine.getStencilBuffer();
  95865. var previousStencilFunction = engine.getStencilFunction();
  95866. var previousStencilMask = engine.getStencilMask();
  95867. var previousStencilOperationPass = engine.getStencilOperationPass();
  95868. var previousStencilOperationFail = engine.getStencilOperationFail();
  95869. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95870. var previousStencilReference = engine.getStencilFunctionReference();
  95871. // Stencil operations
  95872. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95873. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95874. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95875. // Draw order
  95876. engine.setStencilMask(0x00);
  95877. engine.setStencilBuffer(true);
  95878. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95879. // 2 passes inner outer
  95880. if (this.outerGlow) {
  95881. effect.setFloat("offset", 0);
  95882. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95883. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95884. }
  95885. if (this.innerGlow) {
  95886. effect.setFloat("offset", 1);
  95887. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95888. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95889. }
  95890. // Restore Cache
  95891. engine.setStencilFunction(previousStencilFunction);
  95892. engine.setStencilMask(previousStencilMask);
  95893. engine.setStencilBuffer(previousStencilBuffer);
  95894. engine.setStencilOperationPass(previousStencilOperationPass);
  95895. engine.setStencilOperationFail(previousStencilOperationFail);
  95896. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95897. engine.setStencilFunctionReference(previousStencilReference);
  95898. };
  95899. /**
  95900. * Returns true if the layer contains information to display, otherwise false.
  95901. */
  95902. HighlightLayer.prototype.shouldRender = function () {
  95903. if (_super.prototype.shouldRender.call(this)) {
  95904. return this._meshes ? true : false;
  95905. }
  95906. return false;
  95907. };
  95908. /**
  95909. * Returns true if the mesh should render, otherwise false.
  95910. * @param mesh The mesh to render
  95911. * @returns true if it should render otherwise false
  95912. */
  95913. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95914. // Excluded Mesh
  95915. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95916. return false;
  95917. }
  95918. ;
  95919. return true;
  95920. };
  95921. /**
  95922. * Sets the required values for both the emissive texture and and the main color.
  95923. */
  95924. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95925. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95926. if (highlightLayerMesh) {
  95927. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95928. }
  95929. else {
  95930. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95931. }
  95932. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95933. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95934. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95935. }
  95936. else {
  95937. this._emissiveTextureAndColor.texture = null;
  95938. }
  95939. };
  95940. /**
  95941. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95942. * @param mesh The mesh to exclude from the highlight layer
  95943. */
  95944. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95945. if (!this._excludedMeshes) {
  95946. return;
  95947. }
  95948. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95949. if (!meshExcluded) {
  95950. this._excludedMeshes[mesh.uniqueId] = {
  95951. mesh: mesh,
  95952. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95953. mesh.getEngine().setStencilBuffer(false);
  95954. }),
  95955. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95956. mesh.getEngine().setStencilBuffer(true);
  95957. }),
  95958. };
  95959. }
  95960. };
  95961. /**
  95962. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95963. * @param mesh The mesh to highlight
  95964. */
  95965. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95966. if (!this._excludedMeshes) {
  95967. return;
  95968. }
  95969. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95970. if (meshExcluded) {
  95971. if (meshExcluded.beforeRender) {
  95972. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95973. }
  95974. if (meshExcluded.afterRender) {
  95975. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95976. }
  95977. }
  95978. this._excludedMeshes[mesh.uniqueId] = null;
  95979. };
  95980. /**
  95981. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95982. * @param mesh mesh to test
  95983. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95984. */
  95985. HighlightLayer.prototype.hasMesh = function (mesh) {
  95986. if (!this._meshes) {
  95987. return false;
  95988. }
  95989. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95990. };
  95991. /**
  95992. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95993. * @param mesh The mesh to highlight
  95994. * @param color The color of the highlight
  95995. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95996. */
  95997. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95998. var _this = this;
  95999. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96000. if (!this._meshes) {
  96001. return;
  96002. }
  96003. var meshHighlight = this._meshes[mesh.uniqueId];
  96004. if (meshHighlight) {
  96005. meshHighlight.color = color;
  96006. }
  96007. else {
  96008. this._meshes[mesh.uniqueId] = {
  96009. mesh: mesh,
  96010. color: color,
  96011. // Lambda required for capture due to Observable this context
  96012. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96013. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96014. _this._defaultStencilReference(mesh);
  96015. }
  96016. else {
  96017. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96018. }
  96019. }),
  96020. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96021. glowEmissiveOnly: glowEmissiveOnly
  96022. };
  96023. }
  96024. this._shouldRender = true;
  96025. };
  96026. /**
  96027. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96028. * @param mesh The mesh to highlight
  96029. */
  96030. HighlightLayer.prototype.removeMesh = function (mesh) {
  96031. if (!this._meshes) {
  96032. return;
  96033. }
  96034. var meshHighlight = this._meshes[mesh.uniqueId];
  96035. if (meshHighlight) {
  96036. if (meshHighlight.observerHighlight) {
  96037. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96038. }
  96039. if (meshHighlight.observerDefault) {
  96040. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96041. }
  96042. delete this._meshes[mesh.uniqueId];
  96043. }
  96044. this._shouldRender = false;
  96045. for (var meshHighlightToCheck in this._meshes) {
  96046. if (this._meshes[meshHighlightToCheck]) {
  96047. this._shouldRender = true;
  96048. break;
  96049. }
  96050. }
  96051. };
  96052. /**
  96053. * Force the stencil to the normal expected value for none glowing parts
  96054. */
  96055. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96056. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96057. };
  96058. /**
  96059. * Free any resources and references associated to a mesh.
  96060. * Internal use
  96061. * @param mesh The mesh to free.
  96062. */
  96063. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96064. this.removeMesh(mesh);
  96065. this.removeExcludedMesh(mesh);
  96066. };
  96067. /**
  96068. * Dispose the highlight layer and free resources.
  96069. */
  96070. HighlightLayer.prototype.dispose = function () {
  96071. if (this._meshes) {
  96072. // Clean mesh references
  96073. for (var id in this._meshes) {
  96074. var meshHighlight = this._meshes[id];
  96075. if (meshHighlight && meshHighlight.mesh) {
  96076. if (meshHighlight.observerHighlight) {
  96077. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96078. }
  96079. if (meshHighlight.observerDefault) {
  96080. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96081. }
  96082. }
  96083. }
  96084. this._meshes = null;
  96085. }
  96086. if (this._excludedMeshes) {
  96087. for (var id in this._excludedMeshes) {
  96088. var meshHighlight = this._excludedMeshes[id];
  96089. if (meshHighlight) {
  96090. if (meshHighlight.beforeRender) {
  96091. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96092. }
  96093. if (meshHighlight.afterRender) {
  96094. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96095. }
  96096. }
  96097. }
  96098. this._excludedMeshes = null;
  96099. }
  96100. _super.prototype.dispose.call(this);
  96101. };
  96102. /**
  96103. * Gets the class name of the effect layer
  96104. * @returns the string with the class name of the effect layer
  96105. */
  96106. HighlightLayer.prototype.getClassName = function () {
  96107. return "HighlightLayer";
  96108. };
  96109. /**
  96110. * Serializes this Highlight layer
  96111. * @returns a serialized Highlight layer object
  96112. */
  96113. HighlightLayer.prototype.serialize = function () {
  96114. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96115. serializationObject.customType = "BABYLON.HighlightLayer";
  96116. // Highlighted meshes
  96117. serializationObject.meshes = [];
  96118. if (this._meshes) {
  96119. for (var m in this._meshes) {
  96120. var mesh = this._meshes[m];
  96121. if (mesh) {
  96122. serializationObject.meshes.push({
  96123. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96124. color: mesh.color.asArray(),
  96125. meshId: mesh.mesh.id
  96126. });
  96127. }
  96128. }
  96129. }
  96130. // Excluded meshes
  96131. serializationObject.excludedMeshes = [];
  96132. if (this._excludedMeshes) {
  96133. for (var e in this._excludedMeshes) {
  96134. var excludedMesh = this._excludedMeshes[e];
  96135. if (excludedMesh) {
  96136. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96137. }
  96138. }
  96139. }
  96140. return serializationObject;
  96141. };
  96142. /**
  96143. * Creates a Highlight layer from parsed Highlight layer data
  96144. * @param parsedHightlightLayer defines the Highlight layer data
  96145. * @param scene defines the current scene
  96146. * @param rootUrl defines the root URL containing the Highlight layer information
  96147. * @returns a parsed Highlight layer
  96148. */
  96149. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96150. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96151. var index;
  96152. // Excluded meshes
  96153. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96154. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96155. if (mesh) {
  96156. hl.addExcludedMesh(mesh);
  96157. }
  96158. }
  96159. // Included meshes
  96160. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96161. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96162. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96163. if (mesh) {
  96164. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96165. }
  96166. }
  96167. return hl;
  96168. };
  96169. /**
  96170. * Effect Name of the highlight layer.
  96171. */
  96172. HighlightLayer.EffectName = "HighlightLayer";
  96173. /**
  96174. * The neutral color used during the preparation of the glow effect.
  96175. * This is black by default as the blend operation is a blend operation.
  96176. */
  96177. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96178. /**
  96179. * Stencil value used for glowing meshes.
  96180. */
  96181. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96182. /**
  96183. * Stencil value used for the other meshes in the scene.
  96184. */
  96185. HighlightLayer.NormalMeshStencilReference = 0x01;
  96186. __decorate([
  96187. BABYLON.serialize()
  96188. ], HighlightLayer.prototype, "innerGlow", void 0);
  96189. __decorate([
  96190. BABYLON.serialize()
  96191. ], HighlightLayer.prototype, "outerGlow", void 0);
  96192. __decorate([
  96193. BABYLON.serialize()
  96194. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96195. __decorate([
  96196. BABYLON.serialize()
  96197. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96198. __decorate([
  96199. BABYLON.serialize("options")
  96200. ], HighlightLayer.prototype, "_options", void 0);
  96201. return HighlightLayer;
  96202. }(BABYLON.EffectLayer));
  96203. BABYLON.HighlightLayer = HighlightLayer;
  96204. })(BABYLON || (BABYLON = {}));
  96205. //# sourceMappingURL=babylon.highlightLayer.js.map
  96206. var BABYLON;
  96207. (function (BABYLON) {
  96208. /**
  96209. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96210. *
  96211. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96212. * glowy meshes to your scene.
  96213. *
  96214. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96215. */
  96216. var GlowLayer = /** @class */ (function (_super) {
  96217. __extends(GlowLayer, _super);
  96218. /**
  96219. * Instantiates a new glow Layer and references it to the scene.
  96220. * @param name The name of the layer
  96221. * @param scene The scene to use the layer in
  96222. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96223. */
  96224. function GlowLayer(name, scene, options) {
  96225. var _this = _super.call(this, name, scene) || this;
  96226. _this._intensity = 1.0;
  96227. _this._includedOnlyMeshes = [];
  96228. _this._excludedMeshes = [];
  96229. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96230. // Adapt options
  96231. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96232. // Initialize the layer
  96233. _this._init({
  96234. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96235. camera: _this._options.camera,
  96236. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96237. mainTextureRatio: _this._options.mainTextureRatio
  96238. });
  96239. return _this;
  96240. }
  96241. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96242. /**
  96243. * Gets the kernel size of the blur.
  96244. */
  96245. get: function () {
  96246. return this._horizontalBlurPostprocess1.kernel;
  96247. },
  96248. /**
  96249. * Sets the kernel size of the blur.
  96250. */
  96251. set: function (value) {
  96252. this._horizontalBlurPostprocess1.kernel = value;
  96253. this._verticalBlurPostprocess1.kernel = value;
  96254. this._horizontalBlurPostprocess2.kernel = value;
  96255. this._verticalBlurPostprocess2.kernel = value;
  96256. },
  96257. enumerable: true,
  96258. configurable: true
  96259. });
  96260. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96261. /**
  96262. * Gets the glow intensity.
  96263. */
  96264. get: function () {
  96265. return this._intensity;
  96266. },
  96267. /**
  96268. * Sets the glow intensity.
  96269. */
  96270. set: function (value) {
  96271. this._intensity = value;
  96272. },
  96273. enumerable: true,
  96274. configurable: true
  96275. });
  96276. /**
  96277. * Get the effect name of the layer.
  96278. * @return The effect name
  96279. */
  96280. GlowLayer.prototype.getEffectName = function () {
  96281. return GlowLayer.EffectName;
  96282. };
  96283. /**
  96284. * Create the merge effect. This is the shader use to blit the information back
  96285. * to the main canvas at the end of the scene rendering.
  96286. */
  96287. GlowLayer.prototype._createMergeEffect = function () {
  96288. // Effect
  96289. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96290. };
  96291. /**
  96292. * Creates the render target textures and post processes used in the glow layer.
  96293. */
  96294. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96295. var _this = this;
  96296. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96297. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96298. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96299. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96300. var textureType = 0;
  96301. if (this._engine.getCaps().textureHalfFloatRender) {
  96302. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96303. }
  96304. else {
  96305. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96306. }
  96307. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96308. width: blurTextureWidth,
  96309. height: blurTextureHeight
  96310. }, this._scene, false, true, textureType);
  96311. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96312. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96313. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96314. this._blurTexture1.renderParticles = false;
  96315. this._blurTexture1.ignoreCameraViewport = true;
  96316. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96317. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96318. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96319. width: blurTextureWidth2,
  96320. height: blurTextureHeight2
  96321. }, this._scene, false, true, textureType);
  96322. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96323. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96324. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96325. this._blurTexture2.renderParticles = false;
  96326. this._blurTexture2.ignoreCameraViewport = true;
  96327. this._textures = [this._blurTexture1, this._blurTexture2];
  96328. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96329. width: blurTextureWidth,
  96330. height: blurTextureHeight
  96331. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96332. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96333. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96334. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96335. effect.setTexture("textureSampler", _this._mainTexture);
  96336. });
  96337. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96338. width: blurTextureWidth,
  96339. height: blurTextureHeight
  96340. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96341. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96342. width: blurTextureWidth2,
  96343. height: blurTextureHeight2
  96344. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96345. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96346. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96347. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96348. effect.setTexture("textureSampler", _this._blurTexture1);
  96349. });
  96350. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96351. width: blurTextureWidth2,
  96352. height: blurTextureHeight2
  96353. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96354. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96355. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96356. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96357. this._mainTexture.samples = this._options.mainTextureSamples;
  96358. this._mainTexture.onAfterUnbindObservable.add(function () {
  96359. var internalTexture = _this._blurTexture1.getInternalTexture();
  96360. if (internalTexture) {
  96361. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96362. internalTexture = _this._blurTexture2.getInternalTexture();
  96363. if (internalTexture) {
  96364. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96365. }
  96366. }
  96367. });
  96368. // Prevent autoClear.
  96369. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96370. };
  96371. /**
  96372. * Checks for the readiness of the element composing the layer.
  96373. * @param subMesh the mesh to check for
  96374. * @param useInstances specify wether or not to use instances to render the mesh
  96375. * @param emissiveTexture the associated emissive texture used to generate the glow
  96376. * @return true if ready otherwise, false
  96377. */
  96378. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96379. var material = subMesh.getMaterial();
  96380. var mesh = subMesh.getRenderingMesh();
  96381. if (!material || !mesh) {
  96382. return false;
  96383. }
  96384. var emissiveTexture = material.emissiveTexture;
  96385. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96386. };
  96387. /**
  96388. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96389. */
  96390. GlowLayer.prototype.needStencil = function () {
  96391. return false;
  96392. };
  96393. /**
  96394. * Implementation specific of rendering the generating effect on the main canvas.
  96395. * @param effect The effect used to render through
  96396. */
  96397. GlowLayer.prototype._internalRender = function (effect) {
  96398. // Texture
  96399. effect.setTexture("textureSampler", this._blurTexture1);
  96400. effect.setTexture("textureSampler2", this._blurTexture2);
  96401. effect.setFloat("offset", this._intensity);
  96402. // Cache
  96403. var engine = this._engine;
  96404. var previousStencilBuffer = engine.getStencilBuffer();
  96405. // Draw order
  96406. engine.setStencilBuffer(false);
  96407. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96408. // Draw order
  96409. engine.setStencilBuffer(previousStencilBuffer);
  96410. };
  96411. /**
  96412. * Sets the required values for both the emissive texture and and the main color.
  96413. */
  96414. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96415. var textureLevel = 1.0;
  96416. if (this.customEmissiveTextureSelector) {
  96417. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96418. }
  96419. else {
  96420. if (material) {
  96421. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96422. if (this._emissiveTextureAndColor.texture) {
  96423. textureLevel = this._emissiveTextureAndColor.texture.level;
  96424. }
  96425. }
  96426. else {
  96427. this._emissiveTextureAndColor.texture = null;
  96428. }
  96429. }
  96430. if (this.customEmissiveColorSelector) {
  96431. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96432. }
  96433. else {
  96434. if (material.emissiveColor) {
  96435. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96436. }
  96437. else {
  96438. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96439. }
  96440. }
  96441. };
  96442. /**
  96443. * Returns true if the mesh should render, otherwise false.
  96444. * @param mesh The mesh to render
  96445. * @returns true if it should render otherwise false
  96446. */
  96447. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96448. return this.hasMesh(mesh);
  96449. };
  96450. /**
  96451. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96452. * @param mesh The mesh to exclude from the glow layer
  96453. */
  96454. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96455. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96456. this._excludedMeshes.push(mesh.uniqueId);
  96457. }
  96458. };
  96459. /**
  96460. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96461. * @param mesh The mesh to remove
  96462. */
  96463. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96464. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96465. if (index !== -1) {
  96466. this._excludedMeshes.splice(index, 1);
  96467. }
  96468. };
  96469. /**
  96470. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96471. * @param mesh The mesh to include in the glow layer
  96472. */
  96473. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96474. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96475. this._includedOnlyMeshes.push(mesh.uniqueId);
  96476. }
  96477. };
  96478. /**
  96479. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96480. * @param mesh The mesh to remove
  96481. */
  96482. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96483. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96484. if (index !== -1) {
  96485. this._includedOnlyMeshes.splice(index, 1);
  96486. }
  96487. };
  96488. /**
  96489. * Determine if a given mesh will be used in the glow layer
  96490. * @param mesh The mesh to test
  96491. * @returns true if the mesh will be highlighted by the current glow layer
  96492. */
  96493. GlowLayer.prototype.hasMesh = function (mesh) {
  96494. // Included Mesh
  96495. if (this._includedOnlyMeshes.length) {
  96496. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96497. }
  96498. ;
  96499. // Excluded Mesh
  96500. if (this._excludedMeshes.length) {
  96501. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96502. }
  96503. ;
  96504. return true;
  96505. };
  96506. /**
  96507. * Free any resources and references associated to a mesh.
  96508. * Internal use
  96509. * @param mesh The mesh to free.
  96510. */
  96511. GlowLayer.prototype._disposeMesh = function (mesh) {
  96512. this.removeIncludedOnlyMesh(mesh);
  96513. this.removeExcludedMesh(mesh);
  96514. };
  96515. /**
  96516. * Gets the class name of the effect layer
  96517. * @returns the string with the class name of the effect layer
  96518. */
  96519. GlowLayer.prototype.getClassName = function () {
  96520. return "GlowLayer";
  96521. };
  96522. /**
  96523. * Serializes this glow layer
  96524. * @returns a serialized glow layer object
  96525. */
  96526. GlowLayer.prototype.serialize = function () {
  96527. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96528. serializationObject.customType = "BABYLON.GlowLayer";
  96529. var index;
  96530. // Included meshes
  96531. serializationObject.includedMeshes = [];
  96532. if (this._includedOnlyMeshes.length) {
  96533. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96534. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96535. if (mesh) {
  96536. serializationObject.includedMeshes.push(mesh.id);
  96537. }
  96538. }
  96539. }
  96540. // Excluded meshes
  96541. serializationObject.excludedMeshes = [];
  96542. if (this._excludedMeshes.length) {
  96543. for (index = 0; index < this._excludedMeshes.length; index++) {
  96544. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96545. if (mesh) {
  96546. serializationObject.excludedMeshes.push(mesh.id);
  96547. }
  96548. }
  96549. }
  96550. return serializationObject;
  96551. };
  96552. /**
  96553. * Creates a Glow Layer from parsed glow layer data
  96554. * @param parsedGlowLayer defines glow layer data
  96555. * @param scene defines the current scene
  96556. * @param rootUrl defines the root URL containing the glow layer information
  96557. * @returns a parsed Glow Layer
  96558. */
  96559. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96560. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96561. var index;
  96562. // Excluded meshes
  96563. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96564. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96565. if (mesh) {
  96566. gl.addExcludedMesh(mesh);
  96567. }
  96568. }
  96569. // Included meshes
  96570. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96571. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96572. if (mesh) {
  96573. gl.addIncludedOnlyMesh(mesh);
  96574. }
  96575. }
  96576. return gl;
  96577. };
  96578. /**
  96579. * Effect Name of the layer.
  96580. */
  96581. GlowLayer.EffectName = "GlowLayer";
  96582. /**
  96583. * The default blur kernel size used for the glow.
  96584. */
  96585. GlowLayer.DefaultBlurKernelSize = 32;
  96586. /**
  96587. * The default texture size ratio used for the glow.
  96588. */
  96589. GlowLayer.DefaultTextureRatio = 0.5;
  96590. __decorate([
  96591. BABYLON.serialize()
  96592. ], GlowLayer.prototype, "blurKernelSize", null);
  96593. __decorate([
  96594. BABYLON.serialize()
  96595. ], GlowLayer.prototype, "intensity", null);
  96596. __decorate([
  96597. BABYLON.serialize("options")
  96598. ], GlowLayer.prototype, "_options", void 0);
  96599. return GlowLayer;
  96600. }(BABYLON.EffectLayer));
  96601. BABYLON.GlowLayer = GlowLayer;
  96602. })(BABYLON || (BABYLON = {}));
  96603. //# sourceMappingURL=babylon.glowLayer.js.map
  96604. var BABYLON;
  96605. (function (BABYLON) {
  96606. /**
  96607. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96608. */
  96609. var AssetTaskState;
  96610. (function (AssetTaskState) {
  96611. /**
  96612. * Initialization
  96613. */
  96614. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96615. /**
  96616. * Running
  96617. */
  96618. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96619. /**
  96620. * Done
  96621. */
  96622. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96623. /**
  96624. * Error
  96625. */
  96626. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96627. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96628. /**
  96629. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96630. */
  96631. var AbstractAssetTask = /** @class */ (function () {
  96632. /**
  96633. * Creates a new {BABYLON.AssetsManager}
  96634. * @param name defines the name of the task
  96635. */
  96636. function AbstractAssetTask(
  96637. /**
  96638. * Task name
  96639. */ name) {
  96640. this.name = name;
  96641. this._isCompleted = false;
  96642. this._taskState = AssetTaskState.INIT;
  96643. }
  96644. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96645. /**
  96646. * Get if the task is completed
  96647. */
  96648. get: function () {
  96649. return this._isCompleted;
  96650. },
  96651. enumerable: true,
  96652. configurable: true
  96653. });
  96654. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96655. /**
  96656. * Gets the current state of the task
  96657. */
  96658. get: function () {
  96659. return this._taskState;
  96660. },
  96661. enumerable: true,
  96662. configurable: true
  96663. });
  96664. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96665. /**
  96666. * Gets the current error object (if task is in error)
  96667. */
  96668. get: function () {
  96669. return this._errorObject;
  96670. },
  96671. enumerable: true,
  96672. configurable: true
  96673. });
  96674. /**
  96675. * Internal only
  96676. * @hidden
  96677. */
  96678. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96679. if (this._errorObject) {
  96680. return;
  96681. }
  96682. this._errorObject = {
  96683. message: message,
  96684. exception: exception
  96685. };
  96686. };
  96687. /**
  96688. * Execute the current task
  96689. * @param scene defines the scene where you want your assets to be loaded
  96690. * @param onSuccess is a callback called when the task is successfully executed
  96691. * @param onError is a callback called if an error occurs
  96692. */
  96693. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96694. var _this = this;
  96695. this._taskState = AssetTaskState.RUNNING;
  96696. this.runTask(scene, function () {
  96697. _this.onDoneCallback(onSuccess, onError);
  96698. }, function (msg, exception) {
  96699. _this.onErrorCallback(onError, msg, exception);
  96700. });
  96701. };
  96702. /**
  96703. * Execute the current task
  96704. * @param scene defines the scene where you want your assets to be loaded
  96705. * @param onSuccess is a callback called when the task is successfully executed
  96706. * @param onError is a callback called if an error occurs
  96707. */
  96708. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96709. throw new Error("runTask is not implemented");
  96710. };
  96711. /**
  96712. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96713. * This can be used with failed tasks that have the reason for failure fixed.
  96714. */
  96715. AbstractAssetTask.prototype.reset = function () {
  96716. this._taskState = AssetTaskState.INIT;
  96717. };
  96718. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96719. this._taskState = AssetTaskState.ERROR;
  96720. this._errorObject = {
  96721. message: message,
  96722. exception: exception
  96723. };
  96724. if (this.onError) {
  96725. this.onError(this, message, exception);
  96726. }
  96727. onError();
  96728. };
  96729. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96730. try {
  96731. this._taskState = AssetTaskState.DONE;
  96732. this._isCompleted = true;
  96733. if (this.onSuccess) {
  96734. this.onSuccess(this);
  96735. }
  96736. onSuccess();
  96737. }
  96738. catch (e) {
  96739. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96740. }
  96741. };
  96742. return AbstractAssetTask;
  96743. }());
  96744. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96745. /**
  96746. * Class used to share progress information about assets loading
  96747. */
  96748. var AssetsProgressEvent = /** @class */ (function () {
  96749. /**
  96750. * Creates a {BABYLON.AssetsProgressEvent}
  96751. * @param remainingCount defines the number of remaining tasks to process
  96752. * @param totalCount defines the total number of tasks
  96753. * @param task defines the task that was just processed
  96754. */
  96755. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96756. this.remainingCount = remainingCount;
  96757. this.totalCount = totalCount;
  96758. this.task = task;
  96759. }
  96760. return AssetsProgressEvent;
  96761. }());
  96762. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96763. /**
  96764. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96765. */
  96766. var MeshAssetTask = /** @class */ (function (_super) {
  96767. __extends(MeshAssetTask, _super);
  96768. /**
  96769. * Creates a new {BABYLON.MeshAssetTask}
  96770. * @param name defines the name of the task
  96771. * @param meshesNames defines the list of mesh's names you want to load
  96772. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96773. * @param sceneFilename defines the filename of the scene to load from
  96774. */
  96775. function MeshAssetTask(
  96776. /**
  96777. * Defines the name of the task
  96778. */
  96779. name,
  96780. /**
  96781. * Defines the list of mesh's names you want to load
  96782. */
  96783. meshesNames,
  96784. /**
  96785. * Defines the root url to use as a base to load your meshes and associated resources
  96786. */
  96787. rootUrl,
  96788. /**
  96789. * Defines the filename of the scene to load from
  96790. */
  96791. sceneFilename) {
  96792. var _this = _super.call(this, name) || this;
  96793. _this.name = name;
  96794. _this.meshesNames = meshesNames;
  96795. _this.rootUrl = rootUrl;
  96796. _this.sceneFilename = sceneFilename;
  96797. return _this;
  96798. }
  96799. /**
  96800. * Execute the current task
  96801. * @param scene defines the scene where you want your assets to be loaded
  96802. * @param onSuccess is a callback called when the task is successfully executed
  96803. * @param onError is a callback called if an error occurs
  96804. */
  96805. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96806. var _this = this;
  96807. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96808. _this.loadedMeshes = meshes;
  96809. _this.loadedParticleSystems = particleSystems;
  96810. _this.loadedSkeletons = skeletons;
  96811. onSuccess();
  96812. }, null, function (scene, message, exception) {
  96813. onError(message, exception);
  96814. });
  96815. };
  96816. return MeshAssetTask;
  96817. }(AbstractAssetTask));
  96818. BABYLON.MeshAssetTask = MeshAssetTask;
  96819. /**
  96820. * Define a task used by {BABYLON.AssetsManager} to load text content
  96821. */
  96822. var TextFileAssetTask = /** @class */ (function (_super) {
  96823. __extends(TextFileAssetTask, _super);
  96824. /**
  96825. * Creates a new TextFileAssetTask object
  96826. * @param name defines the name of the task
  96827. * @param url defines the location of the file to load
  96828. */
  96829. function TextFileAssetTask(
  96830. /**
  96831. * Defines the name of the task
  96832. */
  96833. name,
  96834. /**
  96835. * Defines the location of the file to load
  96836. */
  96837. url) {
  96838. var _this = _super.call(this, name) || this;
  96839. _this.name = name;
  96840. _this.url = url;
  96841. return _this;
  96842. }
  96843. /**
  96844. * Execute the current task
  96845. * @param scene defines the scene where you want your assets to be loaded
  96846. * @param onSuccess is a callback called when the task is successfully executed
  96847. * @param onError is a callback called if an error occurs
  96848. */
  96849. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96850. var _this = this;
  96851. scene._loadFile(this.url, function (data) {
  96852. _this.text = data;
  96853. onSuccess();
  96854. }, undefined, false, false, function (request, exception) {
  96855. if (request) {
  96856. onError(request.status + " " + request.statusText, exception);
  96857. }
  96858. });
  96859. };
  96860. return TextFileAssetTask;
  96861. }(AbstractAssetTask));
  96862. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96863. /**
  96864. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96865. */
  96866. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96867. __extends(BinaryFileAssetTask, _super);
  96868. /**
  96869. * Creates a new BinaryFileAssetTask object
  96870. * @param name defines the name of the new task
  96871. * @param url defines the location of the file to load
  96872. */
  96873. function BinaryFileAssetTask(
  96874. /**
  96875. * Defines the name of the task
  96876. */
  96877. name,
  96878. /**
  96879. * Defines the location of the file to load
  96880. */
  96881. url) {
  96882. var _this = _super.call(this, name) || this;
  96883. _this.name = name;
  96884. _this.url = url;
  96885. return _this;
  96886. }
  96887. /**
  96888. * Execute the current task
  96889. * @param scene defines the scene where you want your assets to be loaded
  96890. * @param onSuccess is a callback called when the task is successfully executed
  96891. * @param onError is a callback called if an error occurs
  96892. */
  96893. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96894. var _this = this;
  96895. scene._loadFile(this.url, function (data) {
  96896. _this.data = data;
  96897. onSuccess();
  96898. }, undefined, true, true, function (request, exception) {
  96899. if (request) {
  96900. onError(request.status + " " + request.statusText, exception);
  96901. }
  96902. });
  96903. };
  96904. return BinaryFileAssetTask;
  96905. }(AbstractAssetTask));
  96906. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96907. /**
  96908. * Define a task used by {BABYLON.AssetsManager} to load images
  96909. */
  96910. var ImageAssetTask = /** @class */ (function (_super) {
  96911. __extends(ImageAssetTask, _super);
  96912. /**
  96913. * Creates a new ImageAssetTask
  96914. * @param name defines the name of the task
  96915. * @param url defines the location of the image to load
  96916. */
  96917. function ImageAssetTask(
  96918. /**
  96919. * Defines the name of the task
  96920. */
  96921. name,
  96922. /**
  96923. * Defines the location of the image to load
  96924. */
  96925. url) {
  96926. var _this = _super.call(this, name) || this;
  96927. _this.name = name;
  96928. _this.url = url;
  96929. return _this;
  96930. }
  96931. /**
  96932. * Execute the current task
  96933. * @param scene defines the scene where you want your assets to be loaded
  96934. * @param onSuccess is a callback called when the task is successfully executed
  96935. * @param onError is a callback called if an error occurs
  96936. */
  96937. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96938. var _this = this;
  96939. var img = new Image();
  96940. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96941. img.onload = function () {
  96942. _this.image = img;
  96943. onSuccess();
  96944. };
  96945. img.onerror = function (err) {
  96946. onError("Error loading image", err);
  96947. };
  96948. img.src = this.url;
  96949. };
  96950. return ImageAssetTask;
  96951. }(AbstractAssetTask));
  96952. BABYLON.ImageAssetTask = ImageAssetTask;
  96953. /**
  96954. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96955. */
  96956. var TextureAssetTask = /** @class */ (function (_super) {
  96957. __extends(TextureAssetTask, _super);
  96958. /**
  96959. * Creates a new TextureAssetTask object
  96960. * @param name defines the name of the task
  96961. * @param url defines the location of the file to load
  96962. * @param noMipmap defines if mipmap should not be generated (default is false)
  96963. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96964. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96965. */
  96966. function TextureAssetTask(
  96967. /**
  96968. * Defines the name of the task
  96969. */
  96970. name,
  96971. /**
  96972. * Defines the location of the file to load
  96973. */
  96974. url,
  96975. /**
  96976. * Defines if mipmap should not be generated (default is false)
  96977. */
  96978. noMipmap,
  96979. /**
  96980. * Defines if texture must be inverted on Y axis (default is false)
  96981. */
  96982. invertY,
  96983. /**
  96984. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96985. */
  96986. samplingMode) {
  96987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96988. var _this = _super.call(this, name) || this;
  96989. _this.name = name;
  96990. _this.url = url;
  96991. _this.noMipmap = noMipmap;
  96992. _this.invertY = invertY;
  96993. _this.samplingMode = samplingMode;
  96994. return _this;
  96995. }
  96996. /**
  96997. * Execute the current task
  96998. * @param scene defines the scene where you want your assets to be loaded
  96999. * @param onSuccess is a callback called when the task is successfully executed
  97000. * @param onError is a callback called if an error occurs
  97001. */
  97002. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97003. var onload = function () {
  97004. onSuccess();
  97005. };
  97006. var onerror = function (message, exception) {
  97007. onError(message, exception);
  97008. };
  97009. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97010. };
  97011. return TextureAssetTask;
  97012. }(AbstractAssetTask));
  97013. BABYLON.TextureAssetTask = TextureAssetTask;
  97014. /**
  97015. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97016. */
  97017. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97018. __extends(CubeTextureAssetTask, _super);
  97019. /**
  97020. * Creates a new CubeTextureAssetTask
  97021. * @param name defines the name of the task
  97022. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97023. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97024. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97025. * @param files defines the explicit list of files (undefined by default)
  97026. */
  97027. function CubeTextureAssetTask(
  97028. /**
  97029. * Defines the name of the task
  97030. */
  97031. name,
  97032. /**
  97033. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97034. */
  97035. url,
  97036. /**
  97037. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97038. */
  97039. extensions,
  97040. /**
  97041. * Defines if mipmaps should not be generated (default is false)
  97042. */
  97043. noMipmap,
  97044. /**
  97045. * Defines the explicit list of files (undefined by default)
  97046. */
  97047. files) {
  97048. var _this = _super.call(this, name) || this;
  97049. _this.name = name;
  97050. _this.url = url;
  97051. _this.extensions = extensions;
  97052. _this.noMipmap = noMipmap;
  97053. _this.files = files;
  97054. return _this;
  97055. }
  97056. /**
  97057. * Execute the current task
  97058. * @param scene defines the scene where you want your assets to be loaded
  97059. * @param onSuccess is a callback called when the task is successfully executed
  97060. * @param onError is a callback called if an error occurs
  97061. */
  97062. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97063. var onload = function () {
  97064. onSuccess();
  97065. };
  97066. var onerror = function (message, exception) {
  97067. onError(message, exception);
  97068. };
  97069. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97070. };
  97071. return CubeTextureAssetTask;
  97072. }(AbstractAssetTask));
  97073. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97074. /**
  97075. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97076. */
  97077. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97078. __extends(HDRCubeTextureAssetTask, _super);
  97079. /**
  97080. * Creates a new HDRCubeTextureAssetTask object
  97081. * @param name defines the name of the task
  97082. * @param url defines the location of the file to load
  97083. * @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.
  97084. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97085. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97086. * @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)
  97087. * @param reserved Internal use only
  97088. */
  97089. function HDRCubeTextureAssetTask(
  97090. /**
  97091. * Defines the name of the task
  97092. */
  97093. name,
  97094. /**
  97095. * Defines the location of the file to load
  97096. */
  97097. url,
  97098. /**
  97099. * Defines the desired size (the more it increases the longer the generation will be)
  97100. */
  97101. size,
  97102. /**
  97103. * Defines if mipmaps should not be generated (default is false)
  97104. */
  97105. noMipmap,
  97106. /**
  97107. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97108. */
  97109. generateHarmonics,
  97110. /**
  97111. * 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)
  97112. */
  97113. gammaSpace,
  97114. /**
  97115. * Internal Use Only
  97116. */
  97117. reserved) {
  97118. if (noMipmap === void 0) { noMipmap = false; }
  97119. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97120. if (gammaSpace === void 0) { gammaSpace = false; }
  97121. if (reserved === void 0) { reserved = false; }
  97122. var _this = _super.call(this, name) || this;
  97123. _this.name = name;
  97124. _this.url = url;
  97125. _this.size = size;
  97126. _this.noMipmap = noMipmap;
  97127. _this.generateHarmonics = generateHarmonics;
  97128. _this.gammaSpace = gammaSpace;
  97129. _this.reserved = reserved;
  97130. return _this;
  97131. }
  97132. /**
  97133. * Execute the current task
  97134. * @param scene defines the scene where you want your assets to be loaded
  97135. * @param onSuccess is a callback called when the task is successfully executed
  97136. * @param onError is a callback called if an error occurs
  97137. */
  97138. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97139. var onload = function () {
  97140. onSuccess();
  97141. };
  97142. var onerror = function (message, exception) {
  97143. onError(message, exception);
  97144. };
  97145. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97146. };
  97147. return HDRCubeTextureAssetTask;
  97148. }(AbstractAssetTask));
  97149. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97150. /**
  97151. * This class can be used to easily import assets into a scene
  97152. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97153. */
  97154. var AssetsManager = /** @class */ (function () {
  97155. /**
  97156. * Creates a new AssetsManager
  97157. * @param scene defines the scene to work on
  97158. */
  97159. function AssetsManager(scene) {
  97160. this._isLoading = false;
  97161. this._tasks = new Array();
  97162. this._waitingTasksCount = 0;
  97163. this._totalTasksCount = 0;
  97164. /**
  97165. * Observable called when all tasks are processed
  97166. */
  97167. this.onTaskSuccessObservable = new BABYLON.Observable();
  97168. /**
  97169. * Observable called when a task had an error
  97170. */
  97171. this.onTaskErrorObservable = new BABYLON.Observable();
  97172. /**
  97173. * Observable called when a task is successful
  97174. */
  97175. this.onTasksDoneObservable = new BABYLON.Observable();
  97176. /**
  97177. * Observable called when a task is done (whatever the result is)
  97178. */
  97179. this.onProgressObservable = new BABYLON.Observable();
  97180. /**
  97181. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97182. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97183. */
  97184. this.useDefaultLoadingScreen = true;
  97185. this._scene = scene;
  97186. }
  97187. /**
  97188. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97189. * @param taskName defines the name of the new task
  97190. * @param meshesNames defines the name of meshes to load
  97191. * @param rootUrl defines the root url to use to locate files
  97192. * @param sceneFilename defines the filename of the scene file
  97193. * @returns a new {BABYLON.MeshAssetTask} object
  97194. */
  97195. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97196. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97197. this._tasks.push(task);
  97198. return task;
  97199. };
  97200. /**
  97201. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97202. * @param taskName defines the name of the new task
  97203. * @param url defines the url of the file to load
  97204. * @returns a new {BABYLON.TextFileAssetTask} object
  97205. */
  97206. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97207. var task = new TextFileAssetTask(taskName, url);
  97208. this._tasks.push(task);
  97209. return task;
  97210. };
  97211. /**
  97212. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97213. * @param taskName defines the name of the new task
  97214. * @param url defines the url of the file to load
  97215. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97216. */
  97217. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97218. var task = new BinaryFileAssetTask(taskName, url);
  97219. this._tasks.push(task);
  97220. return task;
  97221. };
  97222. /**
  97223. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97224. * @param taskName defines the name of the new task
  97225. * @param url defines the url of the file to load
  97226. * @returns a new {BABYLON.ImageAssetTask} object
  97227. */
  97228. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97229. var task = new ImageAssetTask(taskName, url);
  97230. this._tasks.push(task);
  97231. return task;
  97232. };
  97233. /**
  97234. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97235. * @param taskName defines the name of the new task
  97236. * @param url defines the url of the file to load
  97237. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97238. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97239. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97240. * @returns a new {BABYLON.TextureAssetTask} object
  97241. */
  97242. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97244. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97245. this._tasks.push(task);
  97246. return task;
  97247. };
  97248. /**
  97249. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97250. * @param taskName defines the name of the new task
  97251. * @param url defines the url of the file to load
  97252. * @param extensions defines the extension to use to load the cube map (can be null)
  97253. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97254. * @param files defines the list of files to load (can be null)
  97255. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97256. */
  97257. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97258. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97259. this._tasks.push(task);
  97260. return task;
  97261. };
  97262. /**
  97263. *
  97264. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97265. * @param taskName defines the name of the new task
  97266. * @param url defines the url of the file to load
  97267. * @param size defines the size you want for the cubemap (can be null)
  97268. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97269. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97270. * @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)
  97271. * @param reserved Internal use only
  97272. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97273. */
  97274. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97275. if (noMipmap === void 0) { noMipmap = false; }
  97276. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97277. if (gammaSpace === void 0) { gammaSpace = false; }
  97278. if (reserved === void 0) { reserved = false; }
  97279. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97280. this._tasks.push(task);
  97281. return task;
  97282. };
  97283. /**
  97284. * Remove a task from the assets manager.
  97285. * @param task the task to remove
  97286. */
  97287. AssetsManager.prototype.removeTask = function (task) {
  97288. var index = this._tasks.indexOf(task);
  97289. if (index > -1) {
  97290. this._tasks.splice(index, 1);
  97291. }
  97292. };
  97293. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97294. this._waitingTasksCount--;
  97295. try {
  97296. if (this.onProgress) {
  97297. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97298. }
  97299. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97300. }
  97301. catch (e) {
  97302. BABYLON.Tools.Error("Error running progress callbacks.");
  97303. console.log(e);
  97304. }
  97305. if (this._waitingTasksCount === 0) {
  97306. try {
  97307. if (this.onFinish) {
  97308. this.onFinish(this._tasks);
  97309. }
  97310. // Let's remove successfull tasks
  97311. var currentTasks = this._tasks.slice();
  97312. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97313. var task = currentTasks_1[_i];
  97314. if (task.taskState === AssetTaskState.DONE) {
  97315. var index = this._tasks.indexOf(task);
  97316. if (index > -1) {
  97317. this._tasks.splice(index, 1);
  97318. }
  97319. }
  97320. }
  97321. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97322. }
  97323. catch (e) {
  97324. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97325. console.log(e);
  97326. }
  97327. this._isLoading = false;
  97328. this._scene.getEngine().hideLoadingUI();
  97329. }
  97330. };
  97331. AssetsManager.prototype._runTask = function (task) {
  97332. var _this = this;
  97333. var done = function () {
  97334. try {
  97335. if (_this.onTaskSuccess) {
  97336. _this.onTaskSuccess(task);
  97337. }
  97338. _this.onTaskSuccessObservable.notifyObservers(task);
  97339. _this._decreaseWaitingTasksCount(task);
  97340. }
  97341. catch (e) {
  97342. error("Error executing task success callbacks", e);
  97343. }
  97344. };
  97345. var error = function (message, exception) {
  97346. task._setErrorObject(message, exception);
  97347. if (_this.onTaskError) {
  97348. _this.onTaskError(task);
  97349. }
  97350. _this.onTaskErrorObservable.notifyObservers(task);
  97351. _this._decreaseWaitingTasksCount(task);
  97352. };
  97353. task.run(this._scene, done, error);
  97354. };
  97355. /**
  97356. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97357. * @return the current instance of the {BABYLON.AssetsManager}
  97358. */
  97359. AssetsManager.prototype.reset = function () {
  97360. this._isLoading = false;
  97361. this._tasks = new Array();
  97362. return this;
  97363. };
  97364. /**
  97365. * Start the loading process
  97366. * @return the current instance of the {BABYLON.AssetsManager}
  97367. */
  97368. AssetsManager.prototype.load = function () {
  97369. if (this._isLoading) {
  97370. return this;
  97371. }
  97372. this._isLoading = true;
  97373. this._waitingTasksCount = this._tasks.length;
  97374. this._totalTasksCount = this._tasks.length;
  97375. if (this._waitingTasksCount === 0) {
  97376. this._isLoading = false;
  97377. if (this.onFinish) {
  97378. this.onFinish(this._tasks);
  97379. }
  97380. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97381. return this;
  97382. }
  97383. if (this.useDefaultLoadingScreen) {
  97384. this._scene.getEngine().displayLoadingUI();
  97385. }
  97386. for (var index = 0; index < this._tasks.length; index++) {
  97387. var task = this._tasks[index];
  97388. if (task.taskState === AssetTaskState.INIT) {
  97389. this._runTask(task);
  97390. }
  97391. }
  97392. return this;
  97393. };
  97394. return AssetsManager;
  97395. }());
  97396. BABYLON.AssetsManager = AssetsManager;
  97397. })(BABYLON || (BABYLON = {}));
  97398. //# sourceMappingURL=babylon.assetsManager.js.map
  97399. var BABYLON;
  97400. (function (BABYLON) {
  97401. var serializedGeometries = [];
  97402. var serializeGeometry = function (geometry, serializationGeometries) {
  97403. if (serializedGeometries[geometry.id]) {
  97404. return;
  97405. }
  97406. if (geometry.doNotSerialize) {
  97407. return;
  97408. }
  97409. if (geometry instanceof BABYLON.BoxGeometry) {
  97410. serializationGeometries.boxes.push(geometry.serialize());
  97411. }
  97412. else if (geometry instanceof BABYLON.SphereGeometry) {
  97413. serializationGeometries.spheres.push(geometry.serialize());
  97414. }
  97415. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97416. serializationGeometries.cylinders.push(geometry.serialize());
  97417. }
  97418. else if (geometry instanceof BABYLON.TorusGeometry) {
  97419. serializationGeometries.toruses.push(geometry.serialize());
  97420. }
  97421. else if (geometry instanceof BABYLON.GroundGeometry) {
  97422. serializationGeometries.grounds.push(geometry.serialize());
  97423. }
  97424. else if (geometry instanceof BABYLON.Plane) {
  97425. serializationGeometries.planes.push(geometry.serialize());
  97426. }
  97427. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97428. serializationGeometries.torusKnots.push(geometry.serialize());
  97429. }
  97430. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97431. throw new Error("Unknown primitive type");
  97432. }
  97433. else {
  97434. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97435. }
  97436. serializedGeometries[geometry.id] = true;
  97437. };
  97438. var serializeMesh = function (mesh, serializationScene) {
  97439. var serializationObject = {};
  97440. // Geometry
  97441. var geometry = mesh._geometry;
  97442. if (geometry) {
  97443. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97444. // 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
  97445. serializeGeometry(geometry, serializationScene.geometries);
  97446. }
  97447. }
  97448. // Custom
  97449. if (mesh.serialize) {
  97450. mesh.serialize(serializationObject);
  97451. }
  97452. return serializationObject;
  97453. };
  97454. var finalizeSingleMesh = function (mesh, serializationObject) {
  97455. //only works if the mesh is already loaded
  97456. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97457. //serialize material
  97458. if (mesh.material) {
  97459. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97460. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97461. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97462. serializationObject.multiMaterials.push(mesh.material.serialize());
  97463. }
  97464. }
  97465. else {
  97466. serializationObject.materials = serializationObject.materials || [];
  97467. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97468. serializationObject.materials.push(mesh.material.serialize());
  97469. }
  97470. }
  97471. }
  97472. //serialize geometry
  97473. var geometry = mesh._geometry;
  97474. if (geometry) {
  97475. if (!serializationObject.geometries) {
  97476. serializationObject.geometries = {};
  97477. serializationObject.geometries.boxes = [];
  97478. serializationObject.geometries.spheres = [];
  97479. serializationObject.geometries.cylinders = [];
  97480. serializationObject.geometries.toruses = [];
  97481. serializationObject.geometries.grounds = [];
  97482. serializationObject.geometries.planes = [];
  97483. serializationObject.geometries.torusKnots = [];
  97484. serializationObject.geometries.vertexData = [];
  97485. }
  97486. serializeGeometry(geometry, serializationObject.geometries);
  97487. }
  97488. // Skeletons
  97489. if (mesh.skeleton) {
  97490. serializationObject.skeletons = serializationObject.skeletons || [];
  97491. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97492. }
  97493. //serialize the actual mesh
  97494. serializationObject.meshes = serializationObject.meshes || [];
  97495. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97496. }
  97497. };
  97498. var SceneSerializer = /** @class */ (function () {
  97499. function SceneSerializer() {
  97500. }
  97501. SceneSerializer.ClearCache = function () {
  97502. serializedGeometries = [];
  97503. };
  97504. SceneSerializer.Serialize = function (scene) {
  97505. var serializationObject = {};
  97506. SceneSerializer.ClearCache();
  97507. // Scene
  97508. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97509. serializationObject.autoClear = scene.autoClear;
  97510. serializationObject.clearColor = scene.clearColor.asArray();
  97511. serializationObject.ambientColor = scene.ambientColor.asArray();
  97512. serializationObject.gravity = scene.gravity.asArray();
  97513. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97514. serializationObject.workerCollisions = scene.workerCollisions;
  97515. // Fog
  97516. if (scene.fogMode && scene.fogMode !== 0) {
  97517. serializationObject.fogMode = scene.fogMode;
  97518. serializationObject.fogColor = scene.fogColor.asArray();
  97519. serializationObject.fogStart = scene.fogStart;
  97520. serializationObject.fogEnd = scene.fogEnd;
  97521. serializationObject.fogDensity = scene.fogDensity;
  97522. }
  97523. //Physics
  97524. if (scene.isPhysicsEnabled()) {
  97525. var physicEngine = scene.getPhysicsEngine();
  97526. if (physicEngine) {
  97527. serializationObject.physicsEnabled = true;
  97528. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97529. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97530. }
  97531. }
  97532. // Metadata
  97533. if (scene.metadata) {
  97534. serializationObject.metadata = scene.metadata;
  97535. }
  97536. // Morph targets
  97537. serializationObject.morphTargetManagers = [];
  97538. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97539. var abstractMesh = _a[_i];
  97540. var manager = abstractMesh.morphTargetManager;
  97541. if (manager) {
  97542. serializationObject.morphTargetManagers.push(manager.serialize());
  97543. }
  97544. }
  97545. // Lights
  97546. serializationObject.lights = [];
  97547. var index;
  97548. var light;
  97549. for (index = 0; index < scene.lights.length; index++) {
  97550. light = scene.lights[index];
  97551. if (!light.doNotSerialize) {
  97552. serializationObject.lights.push(light.serialize());
  97553. }
  97554. }
  97555. // Cameras
  97556. serializationObject.cameras = [];
  97557. for (index = 0; index < scene.cameras.length; index++) {
  97558. var camera = scene.cameras[index];
  97559. if (!camera.doNotSerialize) {
  97560. serializationObject.cameras.push(camera.serialize());
  97561. }
  97562. }
  97563. if (scene.activeCamera) {
  97564. serializationObject.activeCameraID = scene.activeCamera.id;
  97565. }
  97566. // Animations
  97567. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97568. // Materials
  97569. serializationObject.materials = [];
  97570. serializationObject.multiMaterials = [];
  97571. var material;
  97572. for (index = 0; index < scene.materials.length; index++) {
  97573. material = scene.materials[index];
  97574. if (!material.doNotSerialize) {
  97575. serializationObject.materials.push(material.serialize());
  97576. }
  97577. }
  97578. // MultiMaterials
  97579. serializationObject.multiMaterials = [];
  97580. for (index = 0; index < scene.multiMaterials.length; index++) {
  97581. var multiMaterial = scene.multiMaterials[index];
  97582. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97583. }
  97584. // Environment texture
  97585. if (scene.environmentTexture) {
  97586. serializationObject.environmentTexture = scene.environmentTexture.name;
  97587. }
  97588. // Skeletons
  97589. serializationObject.skeletons = [];
  97590. for (index = 0; index < scene.skeletons.length; index++) {
  97591. var skeleton = scene.skeletons[index];
  97592. if (!skeleton.doNotSerialize) {
  97593. serializationObject.skeletons.push(skeleton.serialize());
  97594. }
  97595. }
  97596. // Transform nodes
  97597. serializationObject.transformNodes = [];
  97598. for (index = 0; index < scene.transformNodes.length; index++) {
  97599. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97600. }
  97601. // Geometries
  97602. serializationObject.geometries = {};
  97603. serializationObject.geometries.boxes = [];
  97604. serializationObject.geometries.spheres = [];
  97605. serializationObject.geometries.cylinders = [];
  97606. serializationObject.geometries.toruses = [];
  97607. serializationObject.geometries.grounds = [];
  97608. serializationObject.geometries.planes = [];
  97609. serializationObject.geometries.torusKnots = [];
  97610. serializationObject.geometries.vertexData = [];
  97611. serializedGeometries = [];
  97612. var geometries = scene.getGeometries();
  97613. for (index = 0; index < geometries.length; index++) {
  97614. var geometry = geometries[index];
  97615. if (geometry.isReady()) {
  97616. serializeGeometry(geometry, serializationObject.geometries);
  97617. }
  97618. }
  97619. // Meshes
  97620. serializationObject.meshes = [];
  97621. for (index = 0; index < scene.meshes.length; index++) {
  97622. var abstractMesh = scene.meshes[index];
  97623. if (abstractMesh instanceof BABYLON.Mesh) {
  97624. var mesh = abstractMesh;
  97625. if (!mesh.doNotSerialize) {
  97626. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97627. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97628. }
  97629. }
  97630. }
  97631. }
  97632. // Particles Systems
  97633. serializationObject.particleSystems = [];
  97634. for (index = 0; index < scene.particleSystems.length; index++) {
  97635. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97636. }
  97637. // Lens flares
  97638. serializationObject.lensFlareSystems = [];
  97639. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97640. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97641. }
  97642. // Shadows
  97643. serializationObject.shadowGenerators = [];
  97644. for (index = 0; index < scene.lights.length; index++) {
  97645. light = scene.lights[index];
  97646. var shadowGenerator = light.getShadowGenerator();
  97647. if (shadowGenerator) {
  97648. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97649. }
  97650. }
  97651. // Action Manager
  97652. if (scene.actionManager) {
  97653. serializationObject.actions = scene.actionManager.serialize("scene");
  97654. }
  97655. // Audio
  97656. serializationObject.sounds = [];
  97657. for (index = 0; index < scene.soundTracks.length; index++) {
  97658. var soundtrack = scene.soundTracks[index];
  97659. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97660. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97661. }
  97662. }
  97663. // Effect layers
  97664. serializationObject.effectLayers = [];
  97665. for (index = 0; index < scene.effectLayers.length; index++) {
  97666. var layer = scene.effectLayers[index];
  97667. if (layer.serialize) {
  97668. serializationObject.effectLayers.push(layer.serialize());
  97669. }
  97670. }
  97671. return serializationObject;
  97672. };
  97673. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97674. if (withParents === void 0) { withParents = false; }
  97675. if (withChildren === void 0) { withChildren = false; }
  97676. var serializationObject = {};
  97677. SceneSerializer.ClearCache();
  97678. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97679. if (withParents || withChildren) {
  97680. //deliberate for loop! not for each, appended should be processed as well.
  97681. for (var i = 0; i < toSerialize.length; ++i) {
  97682. if (withChildren) {
  97683. toSerialize[i].getDescendants().forEach(function (node) {
  97684. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97685. toSerialize.push(node);
  97686. }
  97687. });
  97688. }
  97689. //make sure the array doesn't contain the object already
  97690. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97691. toSerialize.push(toSerialize[i].parent);
  97692. }
  97693. }
  97694. }
  97695. toSerialize.forEach(function (mesh) {
  97696. finalizeSingleMesh(mesh, serializationObject);
  97697. });
  97698. return serializationObject;
  97699. };
  97700. return SceneSerializer;
  97701. }());
  97702. BABYLON.SceneSerializer = SceneSerializer;
  97703. })(BABYLON || (BABYLON = {}));
  97704. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97705. var BABYLON;
  97706. (function (BABYLON) {
  97707. var ReflectionProbe = /** @class */ (function () {
  97708. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97709. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97710. var _this = this;
  97711. this.name = name;
  97712. this._viewMatrix = BABYLON.Matrix.Identity();
  97713. this._target = BABYLON.Vector3.Zero();
  97714. this._add = BABYLON.Vector3.Zero();
  97715. this._invertYAxis = false;
  97716. this.position = BABYLON.Vector3.Zero();
  97717. this._scene = scene;
  97718. this._scene.reflectionProbes.push(this);
  97719. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97720. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97721. switch (faceIndex) {
  97722. case 0:
  97723. _this._add.copyFromFloats(1, 0, 0);
  97724. break;
  97725. case 1:
  97726. _this._add.copyFromFloats(-1, 0, 0);
  97727. break;
  97728. case 2:
  97729. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97730. break;
  97731. case 3:
  97732. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97733. break;
  97734. case 4:
  97735. _this._add.copyFromFloats(0, 0, 1);
  97736. break;
  97737. case 5:
  97738. _this._add.copyFromFloats(0, 0, -1);
  97739. break;
  97740. }
  97741. if (_this._attachedMesh) {
  97742. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97743. }
  97744. _this.position.addToRef(_this._add, _this._target);
  97745. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97746. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97747. scene._forcedViewPosition = _this.position;
  97748. });
  97749. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97750. scene._forcedViewPosition = null;
  97751. scene.updateTransformMatrix(true);
  97752. });
  97753. if (scene.activeCamera) {
  97754. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97755. }
  97756. }
  97757. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97758. get: function () {
  97759. return this._renderTargetTexture.samples;
  97760. },
  97761. set: function (value) {
  97762. this._renderTargetTexture.samples = value;
  97763. },
  97764. enumerable: true,
  97765. configurable: true
  97766. });
  97767. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97768. get: function () {
  97769. return this._renderTargetTexture.refreshRate;
  97770. },
  97771. set: function (value) {
  97772. this._renderTargetTexture.refreshRate = value;
  97773. },
  97774. enumerable: true,
  97775. configurable: true
  97776. });
  97777. ReflectionProbe.prototype.getScene = function () {
  97778. return this._scene;
  97779. };
  97780. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97781. get: function () {
  97782. return this._renderTargetTexture;
  97783. },
  97784. enumerable: true,
  97785. configurable: true
  97786. });
  97787. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97788. get: function () {
  97789. return this._renderTargetTexture.renderList;
  97790. },
  97791. enumerable: true,
  97792. configurable: true
  97793. });
  97794. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97795. this._attachedMesh = mesh;
  97796. };
  97797. /**
  97798. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97799. *
  97800. * @param renderingGroupId The rendering group id corresponding to its index
  97801. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97802. */
  97803. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97804. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97805. };
  97806. ReflectionProbe.prototype.dispose = function () {
  97807. var index = this._scene.reflectionProbes.indexOf(this);
  97808. if (index !== -1) {
  97809. // Remove from the scene if found
  97810. this._scene.reflectionProbes.splice(index, 1);
  97811. }
  97812. if (this._renderTargetTexture) {
  97813. this._renderTargetTexture.dispose();
  97814. this._renderTargetTexture = null;
  97815. }
  97816. };
  97817. return ReflectionProbe;
  97818. }());
  97819. BABYLON.ReflectionProbe = ReflectionProbe;
  97820. })(BABYLON || (BABYLON = {}));
  97821. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97822. var BABYLON;
  97823. (function (BABYLON) {
  97824. var Layer = /** @class */ (function () {
  97825. function Layer(name, imgUrl, scene, isBackground, color) {
  97826. this.name = name;
  97827. this.scale = new BABYLON.Vector2(1, 1);
  97828. this.offset = new BABYLON.Vector2(0, 0);
  97829. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97830. this.layerMask = 0x0FFFFFFF;
  97831. this._vertexBuffers = {};
  97832. // Events
  97833. /**
  97834. * An event triggered when the layer is disposed.
  97835. */
  97836. this.onDisposeObservable = new BABYLON.Observable();
  97837. /**
  97838. * An event triggered before rendering the scene
  97839. */
  97840. this.onBeforeRenderObservable = new BABYLON.Observable();
  97841. /**
  97842. * An event triggered after rendering the scene
  97843. */
  97844. this.onAfterRenderObservable = new BABYLON.Observable();
  97845. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97846. this.isBackground = isBackground === undefined ? true : isBackground;
  97847. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97848. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97849. this._scene.layers.push(this);
  97850. var engine = this._scene.getEngine();
  97851. // VBO
  97852. var vertices = [];
  97853. vertices.push(1, 1);
  97854. vertices.push(-1, 1);
  97855. vertices.push(-1, -1);
  97856. vertices.push(1, -1);
  97857. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97859. this._createIndexBuffer();
  97860. // Effects
  97861. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97862. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97863. }
  97864. Object.defineProperty(Layer.prototype, "onDispose", {
  97865. set: function (callback) {
  97866. if (this._onDisposeObserver) {
  97867. this.onDisposeObservable.remove(this._onDisposeObserver);
  97868. }
  97869. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97870. },
  97871. enumerable: true,
  97872. configurable: true
  97873. });
  97874. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97875. set: function (callback) {
  97876. if (this._onBeforeRenderObserver) {
  97877. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97878. }
  97879. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97880. },
  97881. enumerable: true,
  97882. configurable: true
  97883. });
  97884. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97885. set: function (callback) {
  97886. if (this._onAfterRenderObserver) {
  97887. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97888. }
  97889. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97890. },
  97891. enumerable: true,
  97892. configurable: true
  97893. });
  97894. Layer.prototype._createIndexBuffer = function () {
  97895. var engine = this._scene.getEngine();
  97896. // Indices
  97897. var indices = [];
  97898. indices.push(0);
  97899. indices.push(1);
  97900. indices.push(2);
  97901. indices.push(0);
  97902. indices.push(2);
  97903. indices.push(3);
  97904. this._indexBuffer = engine.createIndexBuffer(indices);
  97905. };
  97906. Layer.prototype._rebuild = function () {
  97907. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97908. if (vb) {
  97909. vb._rebuild();
  97910. }
  97911. this._createIndexBuffer();
  97912. };
  97913. Layer.prototype.render = function () {
  97914. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97915. // Check
  97916. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97917. return;
  97918. var engine = this._scene.getEngine();
  97919. this.onBeforeRenderObservable.notifyObservers(this);
  97920. // Render
  97921. engine.enableEffect(currentEffect);
  97922. engine.setState(false);
  97923. // Texture
  97924. currentEffect.setTexture("textureSampler", this.texture);
  97925. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97926. // Color
  97927. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97928. // Scale / offset
  97929. currentEffect.setVector2("offset", this.offset);
  97930. currentEffect.setVector2("scale", this.scale);
  97931. // VBOs
  97932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97933. // Draw order
  97934. if (!this.alphaTest) {
  97935. engine.setAlphaMode(this.alphaBlendingMode);
  97936. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97937. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97938. }
  97939. else {
  97940. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97941. }
  97942. this.onAfterRenderObservable.notifyObservers(this);
  97943. };
  97944. Layer.prototype.dispose = function () {
  97945. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97946. if (vertexBuffer) {
  97947. vertexBuffer.dispose();
  97948. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97949. }
  97950. if (this._indexBuffer) {
  97951. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97952. this._indexBuffer = null;
  97953. }
  97954. if (this.texture) {
  97955. this.texture.dispose();
  97956. this.texture = null;
  97957. }
  97958. // Remove from scene
  97959. var index = this._scene.layers.indexOf(this);
  97960. this._scene.layers.splice(index, 1);
  97961. // Callback
  97962. this.onDisposeObservable.notifyObservers(this);
  97963. this.onDisposeObservable.clear();
  97964. this.onAfterRenderObservable.clear();
  97965. this.onBeforeRenderObservable.clear();
  97966. };
  97967. return Layer;
  97968. }());
  97969. BABYLON.Layer = Layer;
  97970. })(BABYLON || (BABYLON = {}));
  97971. //# sourceMappingURL=babylon.layer.js.map
  97972. var BABYLON;
  97973. (function (BABYLON) {
  97974. var TextureTools = /** @class */ (function () {
  97975. function TextureTools() {
  97976. }
  97977. /**
  97978. * Uses the GPU to create a copy texture rescaled at a given size
  97979. * @param texture Texture to copy from
  97980. * @param width Desired width
  97981. * @param height Desired height
  97982. * @return Generated texture
  97983. */
  97984. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97985. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97986. var scene = texture.getScene();
  97987. var engine = scene.getEngine();
  97988. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97989. rtt.wrapU = texture.wrapU;
  97990. rtt.wrapV = texture.wrapV;
  97991. rtt.uOffset = texture.uOffset;
  97992. rtt.vOffset = texture.vOffset;
  97993. rtt.uScale = texture.uScale;
  97994. rtt.vScale = texture.vScale;
  97995. rtt.uAng = texture.uAng;
  97996. rtt.vAng = texture.vAng;
  97997. rtt.wAng = texture.wAng;
  97998. rtt.coordinatesIndex = texture.coordinatesIndex;
  97999. rtt.level = texture.level;
  98000. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98001. rtt._texture.isReady = false;
  98002. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98003. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98004. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98005. passPostProcess.getEffect().executeWhenCompiled(function () {
  98006. passPostProcess.onApply = function (effect) {
  98007. effect.setTexture("textureSampler", texture);
  98008. };
  98009. var internalTexture = rtt.getInternalTexture();
  98010. if (internalTexture) {
  98011. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98012. engine.unBindFramebuffer(internalTexture);
  98013. rtt.disposeFramebufferObjects();
  98014. passPostProcess.dispose();
  98015. internalTexture.isReady = true;
  98016. }
  98017. });
  98018. return rtt;
  98019. };
  98020. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98021. if (!scene._environmentBRDFTexture) {
  98022. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98023. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98024. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98025. scene._environmentBRDFTexture = texture;
  98026. }
  98027. return scene._environmentBRDFTexture;
  98028. };
  98029. 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=";
  98030. return TextureTools;
  98031. }());
  98032. BABYLON.TextureTools = TextureTools;
  98033. })(BABYLON || (BABYLON = {}));
  98034. //# sourceMappingURL=babylon.textureTools.js.map
  98035. var BABYLON;
  98036. (function (BABYLON) {
  98037. var FramingBehavior = /** @class */ (function () {
  98038. function FramingBehavior() {
  98039. this._mode = FramingBehavior.FitFrustumSidesMode;
  98040. this._radiusScale = 1.0;
  98041. this._positionScale = 0.5;
  98042. this._defaultElevation = 0.3;
  98043. this._elevationReturnTime = 1500;
  98044. this._elevationReturnWaitTime = 1000;
  98045. this._zoomStopsAnimation = false;
  98046. this._framingTime = 1500;
  98047. this._isPointerDown = false;
  98048. this._lastInteractionTime = -Infinity;
  98049. // Framing control
  98050. this._animatables = new Array();
  98051. this._betaIsAnimating = false;
  98052. }
  98053. Object.defineProperty(FramingBehavior.prototype, "name", {
  98054. get: function () {
  98055. return "Framing";
  98056. },
  98057. enumerable: true,
  98058. configurable: true
  98059. });
  98060. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98061. /**
  98062. * Gets current mode used by the behavior.
  98063. */
  98064. get: function () {
  98065. return this._mode;
  98066. },
  98067. /**
  98068. * Sets the current mode used by the behavior
  98069. */
  98070. set: function (mode) {
  98071. this._mode = mode;
  98072. },
  98073. enumerable: true,
  98074. configurable: true
  98075. });
  98076. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98077. /**
  98078. * Gets the scale applied to the radius
  98079. */
  98080. get: function () {
  98081. return this._radiusScale;
  98082. },
  98083. /**
  98084. * Sets the scale applied to the radius (1 by default)
  98085. */
  98086. set: function (radius) {
  98087. this._radiusScale = radius;
  98088. },
  98089. enumerable: true,
  98090. configurable: true
  98091. });
  98092. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98093. /**
  98094. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98095. */
  98096. get: function () {
  98097. return this._positionScale;
  98098. },
  98099. /**
  98100. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98101. */
  98102. set: function (scale) {
  98103. this._positionScale = scale;
  98104. },
  98105. enumerable: true,
  98106. configurable: true
  98107. });
  98108. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98109. /**
  98110. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98111. * behaviour is triggered, in radians.
  98112. */
  98113. get: function () {
  98114. return this._defaultElevation;
  98115. },
  98116. /**
  98117. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98118. * behaviour is triggered, in radians.
  98119. */
  98120. set: function (elevation) {
  98121. this._defaultElevation = elevation;
  98122. },
  98123. enumerable: true,
  98124. configurable: true
  98125. });
  98126. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98127. /**
  98128. * Gets the time (in milliseconds) taken to return to the default beta position.
  98129. * Negative value indicates camera should not return to default.
  98130. */
  98131. get: function () {
  98132. return this._elevationReturnTime;
  98133. },
  98134. /**
  98135. * Sets the time (in milliseconds) taken to return to the default beta position.
  98136. * Negative value indicates camera should not return to default.
  98137. */
  98138. set: function (speed) {
  98139. this._elevationReturnTime = speed;
  98140. },
  98141. enumerable: true,
  98142. configurable: true
  98143. });
  98144. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98145. /**
  98146. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98147. */
  98148. get: function () {
  98149. return this._elevationReturnWaitTime;
  98150. },
  98151. /**
  98152. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98153. */
  98154. set: function (time) {
  98155. this._elevationReturnWaitTime = time;
  98156. },
  98157. enumerable: true,
  98158. configurable: true
  98159. });
  98160. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98161. /**
  98162. * Gets the flag that indicates if user zooming should stop animation.
  98163. */
  98164. get: function () {
  98165. return this._zoomStopsAnimation;
  98166. },
  98167. /**
  98168. * Sets the flag that indicates if user zooming should stop animation.
  98169. */
  98170. set: function (flag) {
  98171. this._zoomStopsAnimation = flag;
  98172. },
  98173. enumerable: true,
  98174. configurable: true
  98175. });
  98176. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98177. /**
  98178. * Gets the transition time when framing the mesh, in milliseconds
  98179. */
  98180. get: function () {
  98181. return this._framingTime;
  98182. },
  98183. /**
  98184. * Sets the transition time when framing the mesh, in milliseconds
  98185. */
  98186. set: function (time) {
  98187. this._framingTime = time;
  98188. },
  98189. enumerable: true,
  98190. configurable: true
  98191. });
  98192. FramingBehavior.prototype.init = function () {
  98193. // Do notihng
  98194. };
  98195. FramingBehavior.prototype.attach = function (camera) {
  98196. var _this = this;
  98197. this._attachedCamera = camera;
  98198. var scene = this._attachedCamera.getScene();
  98199. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98200. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98201. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98202. _this._isPointerDown = true;
  98203. return;
  98204. }
  98205. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98206. _this._isPointerDown = false;
  98207. }
  98208. });
  98209. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98210. if (mesh) {
  98211. _this.zoomOnMesh(mesh);
  98212. }
  98213. });
  98214. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98215. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98216. _this._applyUserInteraction();
  98217. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98218. // back to the default position after a given timeout
  98219. _this._maintainCameraAboveGround();
  98220. });
  98221. };
  98222. FramingBehavior.prototype.detach = function () {
  98223. if (!this._attachedCamera) {
  98224. return;
  98225. }
  98226. var scene = this._attachedCamera.getScene();
  98227. if (this._onPrePointerObservableObserver) {
  98228. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98229. }
  98230. if (this._onAfterCheckInputsObserver) {
  98231. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98232. }
  98233. if (this._onMeshTargetChangedObserver) {
  98234. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98235. }
  98236. this._attachedCamera = null;
  98237. };
  98238. /**
  98239. * Targets the given mesh and updates zoom level accordingly.
  98240. * @param mesh The mesh to target.
  98241. * @param radius Optional. If a cached radius position already exists, overrides default.
  98242. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98243. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98244. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98245. */
  98246. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98247. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98248. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98249. mesh.computeWorldMatrix(true);
  98250. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98251. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98252. };
  98253. /**
  98254. * Targets the given mesh with its children and updates zoom level accordingly.
  98255. * @param mesh The mesh to target.
  98256. * @param radius Optional. If a cached radius position already exists, overrides default.
  98257. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98258. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98259. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98260. */
  98261. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98262. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98263. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98264. mesh.computeWorldMatrix(true);
  98265. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98266. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98267. };
  98268. /**
  98269. * Targets the given meshes with their children and updates zoom level accordingly.
  98270. * @param meshes The mesh to target.
  98271. * @param radius Optional. If a cached radius position already exists, overrides default.
  98272. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98273. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98274. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98275. */
  98276. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98277. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98278. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98279. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98280. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98281. for (var i = 0; i < meshes.length; i++) {
  98282. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98283. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98284. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98285. }
  98286. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98287. };
  98288. /**
  98289. * Targets the given mesh and updates zoom level accordingly.
  98290. * @param mesh The mesh to target.
  98291. * @param radius Optional. If a cached radius position already exists, overrides default.
  98292. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98293. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98294. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98295. */
  98296. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98297. var _this = this;
  98298. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98299. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98300. var zoomTarget;
  98301. if (!this._attachedCamera) {
  98302. return;
  98303. }
  98304. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98305. var bottom = minimumWorld.y;
  98306. var top = maximumWorld.y;
  98307. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98308. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98309. if (focusOnOriginXZ) {
  98310. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98311. }
  98312. else {
  98313. var centerWorld = minimumWorld.add(radiusWorld);
  98314. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98315. }
  98316. if (!this._vectorTransition) {
  98317. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98318. }
  98319. this._betaIsAnimating = true;
  98320. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98321. if (animatable) {
  98322. this._animatables.push(animatable);
  98323. }
  98324. // sets the radius and lower radius bounds
  98325. // Small delta ensures camera is not always at lower zoom limit.
  98326. var radius = 0;
  98327. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98328. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98329. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98330. radius = position;
  98331. }
  98332. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98333. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98334. if (this._attachedCamera.lowerRadiusLimit === null) {
  98335. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98336. }
  98337. }
  98338. // Set sensibilities
  98339. var extend = maximumWorld.subtract(minimumWorld).length();
  98340. this._attachedCamera.panningSensibility = 5000 / extend;
  98341. this._attachedCamera.wheelPrecision = 100 / radius;
  98342. // transition to new radius
  98343. if (!this._radiusTransition) {
  98344. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98345. }
  98346. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98347. _this.stopAllAnimations();
  98348. if (onAnimationEnd) {
  98349. onAnimationEnd();
  98350. }
  98351. if (_this._attachedCamera) {
  98352. _this._attachedCamera.storeState();
  98353. }
  98354. });
  98355. if (animatable) {
  98356. this._animatables.push(animatable);
  98357. }
  98358. };
  98359. /**
  98360. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98361. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98362. * frustum width.
  98363. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98364. * to fully enclose the mesh in the viewing frustum.
  98365. */
  98366. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98367. var size = maximumWorld.subtract(minimumWorld);
  98368. var boxVectorGlobalDiagonal = size.length();
  98369. var frustumSlope = this._getFrustumSlope();
  98370. // Formula for setting distance
  98371. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98372. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98373. // Horizon distance
  98374. var radius = radiusWithoutFraming * this._radiusScale;
  98375. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98376. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98377. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98378. var camera = this._attachedCamera;
  98379. if (!camera) {
  98380. return 0;
  98381. }
  98382. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98383. // Don't exceed the requested limit
  98384. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98385. }
  98386. // Don't exceed the upper radius limit
  98387. if (camera.upperRadiusLimit) {
  98388. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98389. }
  98390. return distance;
  98391. };
  98392. /**
  98393. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98394. * is automatically returned to its default position (expected to be above ground plane).
  98395. */
  98396. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98397. var _this = this;
  98398. if (this._elevationReturnTime < 0) {
  98399. return;
  98400. }
  98401. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98402. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98403. var limitBeta = Math.PI * 0.5;
  98404. // Bring the camera back up if below the ground plane
  98405. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98406. this._betaIsAnimating = true;
  98407. //Transition to new position
  98408. this.stopAllAnimations();
  98409. if (!this._betaTransition) {
  98410. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98411. }
  98412. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98413. _this._clearAnimationLocks();
  98414. _this.stopAllAnimations();
  98415. });
  98416. if (animatabe) {
  98417. this._animatables.push(animatabe);
  98418. }
  98419. }
  98420. };
  98421. /**
  98422. * Returns the frustum slope based on the canvas ratio and camera FOV
  98423. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98424. */
  98425. FramingBehavior.prototype._getFrustumSlope = function () {
  98426. // Calculate the viewport ratio
  98427. // Aspect Ratio is Height/Width.
  98428. var camera = this._attachedCamera;
  98429. if (!camera) {
  98430. return BABYLON.Vector2.Zero();
  98431. }
  98432. var engine = camera.getScene().getEngine();
  98433. var aspectRatio = engine.getAspectRatio(camera);
  98434. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98435. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98436. var frustumSlopeY = Math.tan(camera.fov / 2);
  98437. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98438. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98439. // along the forward vector.
  98440. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98441. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98442. };
  98443. /**
  98444. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98445. */
  98446. FramingBehavior.prototype._clearAnimationLocks = function () {
  98447. this._betaIsAnimating = false;
  98448. };
  98449. /**
  98450. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98451. */
  98452. FramingBehavior.prototype._applyUserInteraction = function () {
  98453. if (this.isUserIsMoving) {
  98454. this._lastInteractionTime = BABYLON.Tools.Now;
  98455. this.stopAllAnimations();
  98456. this._clearAnimationLocks();
  98457. }
  98458. };
  98459. /**
  98460. * Stops and removes all animations that have been applied to the camera
  98461. */
  98462. FramingBehavior.prototype.stopAllAnimations = function () {
  98463. if (this._attachedCamera) {
  98464. this._attachedCamera.animations = [];
  98465. }
  98466. while (this._animatables.length) {
  98467. if (this._animatables[0]) {
  98468. this._animatables[0].onAnimationEnd = null;
  98469. this._animatables[0].stop();
  98470. }
  98471. this._animatables.shift();
  98472. }
  98473. };
  98474. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98475. /**
  98476. * Gets a value indicating if the user is moving the camera
  98477. */
  98478. get: function () {
  98479. if (!this._attachedCamera) {
  98480. return false;
  98481. }
  98482. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98483. this._attachedCamera.inertialBetaOffset !== 0 ||
  98484. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98485. this._attachedCamera.inertialPanningX !== 0 ||
  98486. this._attachedCamera.inertialPanningY !== 0 ||
  98487. this._isPointerDown;
  98488. },
  98489. enumerable: true,
  98490. configurable: true
  98491. });
  98492. /**
  98493. * The easing function used by animations
  98494. */
  98495. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98496. /**
  98497. * The easing mode used by animations
  98498. */
  98499. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98500. // Statics
  98501. /**
  98502. * The camera can move all the way towards the mesh.
  98503. */
  98504. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98505. /**
  98506. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98507. */
  98508. FramingBehavior.FitFrustumSidesMode = 1;
  98509. return FramingBehavior;
  98510. }());
  98511. BABYLON.FramingBehavior = FramingBehavior;
  98512. })(BABYLON || (BABYLON = {}));
  98513. //# sourceMappingURL=babylon.framingBehavior.js.map
  98514. var BABYLON;
  98515. (function (BABYLON) {
  98516. /**
  98517. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98518. */
  98519. var BouncingBehavior = /** @class */ (function () {
  98520. function BouncingBehavior() {
  98521. /**
  98522. * The duration of the animation, in milliseconds
  98523. */
  98524. this.transitionDuration = 450;
  98525. /**
  98526. * Length of the distance animated by the transition when lower radius is reached
  98527. */
  98528. this.lowerRadiusTransitionRange = 2;
  98529. /**
  98530. * Length of the distance animated by the transition when upper radius is reached
  98531. */
  98532. this.upperRadiusTransitionRange = -2;
  98533. this._autoTransitionRange = false;
  98534. // Animations
  98535. this._radiusIsAnimating = false;
  98536. this._radiusBounceTransition = null;
  98537. this._animatables = new Array();
  98538. }
  98539. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98540. get: function () {
  98541. return "Bouncing";
  98542. },
  98543. enumerable: true,
  98544. configurable: true
  98545. });
  98546. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98547. /**
  98548. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98549. */
  98550. get: function () {
  98551. return this._autoTransitionRange;
  98552. },
  98553. /**
  98554. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98555. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98556. */
  98557. set: function (value) {
  98558. var _this = this;
  98559. if (this._autoTransitionRange === value) {
  98560. return;
  98561. }
  98562. this._autoTransitionRange = value;
  98563. var camera = this._attachedCamera;
  98564. if (!camera) {
  98565. return;
  98566. }
  98567. if (value) {
  98568. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98569. if (!mesh) {
  98570. return;
  98571. }
  98572. mesh.computeWorldMatrix(true);
  98573. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98574. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98575. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98576. });
  98577. }
  98578. else if (this._onMeshTargetChangedObserver) {
  98579. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98580. }
  98581. },
  98582. enumerable: true,
  98583. configurable: true
  98584. });
  98585. BouncingBehavior.prototype.init = function () {
  98586. // Do notihng
  98587. };
  98588. BouncingBehavior.prototype.attach = function (camera) {
  98589. var _this = this;
  98590. this._attachedCamera = camera;
  98591. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98592. if (!_this._attachedCamera) {
  98593. return;
  98594. }
  98595. // Add the bounce animation to the lower radius limit
  98596. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98597. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98598. }
  98599. // Add the bounce animation to the upper radius limit
  98600. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98601. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98602. }
  98603. });
  98604. };
  98605. BouncingBehavior.prototype.detach = function () {
  98606. if (!this._attachedCamera) {
  98607. return;
  98608. }
  98609. if (this._onAfterCheckInputsObserver) {
  98610. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98611. }
  98612. if (this._onMeshTargetChangedObserver) {
  98613. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98614. }
  98615. this._attachedCamera = null;
  98616. };
  98617. /**
  98618. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98619. * @param radiusLimit The limit to check against.
  98620. * @return Bool to indicate if at limit.
  98621. */
  98622. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98623. if (!this._attachedCamera) {
  98624. return false;
  98625. }
  98626. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98627. return true;
  98628. }
  98629. return false;
  98630. };
  98631. /**
  98632. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98633. * @param radiusDelta The delta by which to animate to. Can be negative.
  98634. */
  98635. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98636. var _this = this;
  98637. if (!this._attachedCamera) {
  98638. return;
  98639. }
  98640. if (!this._radiusBounceTransition) {
  98641. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98642. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98643. }
  98644. // Prevent zoom until bounce has completed
  98645. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98646. this._attachedCamera.wheelPrecision = Infinity;
  98647. this._attachedCamera.inertialRadiusOffset = 0;
  98648. // Animate to the radius limit
  98649. this.stopAllAnimations();
  98650. this._radiusIsAnimating = true;
  98651. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98652. if (animatable) {
  98653. this._animatables.push(animatable);
  98654. }
  98655. };
  98656. /**
  98657. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98658. */
  98659. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98660. this._radiusIsAnimating = false;
  98661. if (this._attachedCamera) {
  98662. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98663. }
  98664. };
  98665. /**
  98666. * Stops and removes all animations that have been applied to the camera
  98667. */
  98668. BouncingBehavior.prototype.stopAllAnimations = function () {
  98669. if (this._attachedCamera) {
  98670. this._attachedCamera.animations = [];
  98671. }
  98672. while (this._animatables.length) {
  98673. this._animatables[0].onAnimationEnd = null;
  98674. this._animatables[0].stop();
  98675. this._animatables.shift();
  98676. }
  98677. };
  98678. /**
  98679. * The easing function used by animations
  98680. */
  98681. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98682. /**
  98683. * The easing mode used by animations
  98684. */
  98685. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98686. return BouncingBehavior;
  98687. }());
  98688. BABYLON.BouncingBehavior = BouncingBehavior;
  98689. })(BABYLON || (BABYLON = {}));
  98690. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98691. var BABYLON;
  98692. (function (BABYLON) {
  98693. var AutoRotationBehavior = /** @class */ (function () {
  98694. function AutoRotationBehavior() {
  98695. this._zoomStopsAnimation = false;
  98696. this._idleRotationSpeed = 0.05;
  98697. this._idleRotationWaitTime = 2000;
  98698. this._idleRotationSpinupTime = 2000;
  98699. this._isPointerDown = false;
  98700. this._lastFrameTime = null;
  98701. this._lastInteractionTime = -Infinity;
  98702. this._cameraRotationSpeed = 0;
  98703. this._lastFrameRadius = 0;
  98704. }
  98705. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98706. get: function () {
  98707. return "AutoRotation";
  98708. },
  98709. enumerable: true,
  98710. configurable: true
  98711. });
  98712. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98713. /**
  98714. * Gets the flag that indicates if user zooming should stop animation.
  98715. */
  98716. get: function () {
  98717. return this._zoomStopsAnimation;
  98718. },
  98719. /**
  98720. * Sets the flag that indicates if user zooming should stop animation.
  98721. */
  98722. set: function (flag) {
  98723. this._zoomStopsAnimation = flag;
  98724. },
  98725. enumerable: true,
  98726. configurable: true
  98727. });
  98728. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98729. /**
  98730. * Gets the default speed at which the camera rotates around the model.
  98731. */
  98732. get: function () {
  98733. return this._idleRotationSpeed;
  98734. },
  98735. /**
  98736. * Sets the default speed at which the camera rotates around the model.
  98737. */
  98738. set: function (speed) {
  98739. this._idleRotationSpeed = speed;
  98740. },
  98741. enumerable: true,
  98742. configurable: true
  98743. });
  98744. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98745. /**
  98746. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98747. */
  98748. get: function () {
  98749. return this._idleRotationWaitTime;
  98750. },
  98751. /**
  98752. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98753. */
  98754. set: function (time) {
  98755. this._idleRotationWaitTime = time;
  98756. },
  98757. enumerable: true,
  98758. configurable: true
  98759. });
  98760. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98761. /**
  98762. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98763. */
  98764. get: function () {
  98765. return this._idleRotationSpinupTime;
  98766. },
  98767. /**
  98768. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98769. */
  98770. set: function (time) {
  98771. this._idleRotationSpinupTime = time;
  98772. },
  98773. enumerable: true,
  98774. configurable: true
  98775. });
  98776. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98777. /**
  98778. * Gets a value indicating if the camera is currently rotating because of this behavior
  98779. */
  98780. get: function () {
  98781. return Math.abs(this._cameraRotationSpeed) > 0;
  98782. },
  98783. enumerable: true,
  98784. configurable: true
  98785. });
  98786. AutoRotationBehavior.prototype.init = function () {
  98787. // Do notihng
  98788. };
  98789. AutoRotationBehavior.prototype.attach = function (camera) {
  98790. var _this = this;
  98791. this._attachedCamera = camera;
  98792. var scene = this._attachedCamera.getScene();
  98793. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98794. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98795. _this._isPointerDown = true;
  98796. return;
  98797. }
  98798. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98799. _this._isPointerDown = false;
  98800. }
  98801. });
  98802. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98803. var now = BABYLON.Tools.Now;
  98804. var dt = 0;
  98805. if (_this._lastFrameTime != null) {
  98806. dt = now - _this._lastFrameTime;
  98807. }
  98808. _this._lastFrameTime = now;
  98809. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98810. _this._applyUserInteraction();
  98811. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98812. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98813. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98814. // Step camera rotation by rotation speed
  98815. if (_this._attachedCamera) {
  98816. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98817. }
  98818. });
  98819. };
  98820. AutoRotationBehavior.prototype.detach = function () {
  98821. if (!this._attachedCamera) {
  98822. return;
  98823. }
  98824. var scene = this._attachedCamera.getScene();
  98825. if (this._onPrePointerObservableObserver) {
  98826. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98827. }
  98828. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98829. this._attachedCamera = null;
  98830. };
  98831. /**
  98832. * Returns true if user is scrolling.
  98833. * @return true if user is scrolling.
  98834. */
  98835. AutoRotationBehavior.prototype._userIsZooming = function () {
  98836. if (!this._attachedCamera) {
  98837. return false;
  98838. }
  98839. return this._attachedCamera.inertialRadiusOffset !== 0;
  98840. };
  98841. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98842. if (!this._attachedCamera) {
  98843. return false;
  98844. }
  98845. var zoomHasHitLimit = false;
  98846. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98847. zoomHasHitLimit = true;
  98848. }
  98849. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98850. this._lastFrameRadius = this._attachedCamera.radius;
  98851. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98852. };
  98853. /**
  98854. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98855. */
  98856. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98857. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98858. this._lastInteractionTime = BABYLON.Tools.Now;
  98859. }
  98860. };
  98861. // Tools
  98862. AutoRotationBehavior.prototype._userIsMoving = function () {
  98863. if (!this._attachedCamera) {
  98864. return false;
  98865. }
  98866. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98867. this._attachedCamera.inertialBetaOffset !== 0 ||
  98868. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98869. this._attachedCamera.inertialPanningX !== 0 ||
  98870. this._attachedCamera.inertialPanningY !== 0 ||
  98871. this._isPointerDown;
  98872. };
  98873. return AutoRotationBehavior;
  98874. }());
  98875. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98876. })(BABYLON || (BABYLON = {}));
  98877. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98878. var BABYLON;
  98879. (function (BABYLON) {
  98880. var NullEngineOptions = /** @class */ (function () {
  98881. function NullEngineOptions() {
  98882. this.renderWidth = 512;
  98883. this.renderHeight = 256;
  98884. this.textureSize = 512;
  98885. this.deterministicLockstep = false;
  98886. this.lockstepMaxSteps = 4;
  98887. }
  98888. return NullEngineOptions;
  98889. }());
  98890. BABYLON.NullEngineOptions = NullEngineOptions;
  98891. /**
  98892. * The null engine class provides support for headless version of babylon.js.
  98893. * This can be used in server side scenario or for testing purposes
  98894. */
  98895. var NullEngine = /** @class */ (function (_super) {
  98896. __extends(NullEngine, _super);
  98897. function NullEngine(options) {
  98898. if (options === void 0) { options = new NullEngineOptions(); }
  98899. var _this = _super.call(this, null) || this;
  98900. if (options.deterministicLockstep === undefined) {
  98901. options.deterministicLockstep = false;
  98902. }
  98903. if (options.lockstepMaxSteps === undefined) {
  98904. options.lockstepMaxSteps = 4;
  98905. }
  98906. _this._options = options;
  98907. // Init caps
  98908. // We consider we are on a webgl1 capable device
  98909. _this._caps = new BABYLON.EngineCapabilities();
  98910. _this._caps.maxTexturesImageUnits = 16;
  98911. _this._caps.maxVertexTextureImageUnits = 16;
  98912. _this._caps.maxTextureSize = 512;
  98913. _this._caps.maxCubemapTextureSize = 512;
  98914. _this._caps.maxRenderTextureSize = 512;
  98915. _this._caps.maxVertexAttribs = 16;
  98916. _this._caps.maxVaryingVectors = 16;
  98917. _this._caps.maxFragmentUniformVectors = 16;
  98918. _this._caps.maxVertexUniformVectors = 16;
  98919. // Extensions
  98920. _this._caps.standardDerivatives = false;
  98921. _this._caps.astc = null;
  98922. _this._caps.s3tc = null;
  98923. _this._caps.pvrtc = null;
  98924. _this._caps.etc1 = null;
  98925. _this._caps.etc2 = null;
  98926. _this._caps.textureAnisotropicFilterExtension = null;
  98927. _this._caps.maxAnisotropy = 0;
  98928. _this._caps.uintIndices = false;
  98929. _this._caps.fragmentDepthSupported = false;
  98930. _this._caps.highPrecisionShaderSupported = true;
  98931. _this._caps.colorBufferFloat = false;
  98932. _this._caps.textureFloat = false;
  98933. _this._caps.textureFloatLinearFiltering = false;
  98934. _this._caps.textureFloatRender = false;
  98935. _this._caps.textureHalfFloat = false;
  98936. _this._caps.textureHalfFloatLinearFiltering = false;
  98937. _this._caps.textureHalfFloatRender = false;
  98938. _this._caps.textureLOD = false;
  98939. _this._caps.drawBuffersExtension = false;
  98940. _this._caps.depthTextureExtension = false;
  98941. _this._caps.vertexArrayObject = false;
  98942. _this._caps.instancedArrays = false;
  98943. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98944. // Wrappers
  98945. if (typeof URL === "undefined") {
  98946. URL = {
  98947. createObjectURL: function () { },
  98948. revokeObjectURL: function () { }
  98949. };
  98950. }
  98951. if (typeof Blob === "undefined") {
  98952. Blob = function () { };
  98953. }
  98954. return _this;
  98955. }
  98956. NullEngine.prototype.isDeterministicLockStep = function () {
  98957. return this._options.deterministicLockstep;
  98958. };
  98959. NullEngine.prototype.getLockstepMaxSteps = function () {
  98960. return this._options.lockstepMaxSteps;
  98961. };
  98962. NullEngine.prototype.getHardwareScalingLevel = function () {
  98963. return 1.0;
  98964. };
  98965. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98966. return {
  98967. capacity: 0,
  98968. references: 1,
  98969. is32Bits: false
  98970. };
  98971. };
  98972. NullEngine.prototype.createIndexBuffer = function (indices) {
  98973. return {
  98974. capacity: 0,
  98975. references: 1,
  98976. is32Bits: false
  98977. };
  98978. };
  98979. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98980. if (stencil === void 0) { stencil = false; }
  98981. };
  98982. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98983. if (useScreen === void 0) { useScreen = false; }
  98984. if (!useScreen && this._currentRenderTarget) {
  98985. return this._currentRenderTarget.width;
  98986. }
  98987. return this._options.renderWidth;
  98988. };
  98989. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98990. if (useScreen === void 0) { useScreen = false; }
  98991. if (!useScreen && this._currentRenderTarget) {
  98992. return this._currentRenderTarget.height;
  98993. }
  98994. return this._options.renderHeight;
  98995. };
  98996. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98997. this._cachedViewport = viewport;
  98998. };
  98999. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99000. return {
  99001. transformFeedback: null,
  99002. __SPECTOR_rebuildProgram: null
  99003. };
  99004. };
  99005. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99006. return [];
  99007. };
  99008. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99009. return [];
  99010. };
  99011. NullEngine.prototype.bindSamplers = function (effect) {
  99012. this._currentEffect = null;
  99013. };
  99014. NullEngine.prototype.enableEffect = function (effect) {
  99015. this._currentEffect = effect;
  99016. if (effect.onBind) {
  99017. effect.onBind(effect);
  99018. }
  99019. effect.onBindObservable.notifyObservers(effect);
  99020. };
  99021. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99022. if (zOffset === void 0) { zOffset = 0; }
  99023. if (reverseSide === void 0) { reverseSide = false; }
  99024. };
  99025. NullEngine.prototype.setIntArray = function (uniform, array) {
  99026. };
  99027. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99028. };
  99029. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99030. };
  99031. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99032. };
  99033. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99034. };
  99035. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99036. };
  99037. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99038. };
  99039. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99040. };
  99041. NullEngine.prototype.setArray = function (uniform, array) {
  99042. };
  99043. NullEngine.prototype.setArray2 = function (uniform, array) {
  99044. };
  99045. NullEngine.prototype.setArray3 = function (uniform, array) {
  99046. };
  99047. NullEngine.prototype.setArray4 = function (uniform, array) {
  99048. };
  99049. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99050. };
  99051. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99052. };
  99053. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99054. };
  99055. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99056. };
  99057. NullEngine.prototype.setFloat = function (uniform, value) {
  99058. };
  99059. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99060. };
  99061. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99062. };
  99063. NullEngine.prototype.setBool = function (uniform, bool) {
  99064. };
  99065. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99066. };
  99067. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99068. };
  99069. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99070. };
  99071. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99072. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99073. if (this._alphaMode === mode) {
  99074. return;
  99075. }
  99076. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99077. if (!noDepthWriteChange) {
  99078. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99079. }
  99080. this._alphaMode = mode;
  99081. };
  99082. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99083. };
  99084. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99085. if (this.preventCacheWipeBetweenFrames) {
  99086. return;
  99087. }
  99088. this.resetTextureCache();
  99089. this._currentEffect = null;
  99090. if (bruteForce) {
  99091. this._currentProgram = null;
  99092. this._stencilState.reset();
  99093. this._depthCullingState.reset();
  99094. this._alphaState.reset();
  99095. }
  99096. this._cachedVertexBuffers = null;
  99097. this._cachedIndexBuffer = null;
  99098. this._cachedEffectForVertexBuffers = null;
  99099. };
  99100. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99101. };
  99102. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99103. };
  99104. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99105. };
  99106. NullEngine.prototype._createTexture = function () {
  99107. return {};
  99108. };
  99109. NullEngine.prototype._releaseTexture = function (texture) {
  99110. };
  99111. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99113. if (onLoad === void 0) { onLoad = null; }
  99114. if (onError === void 0) { onError = null; }
  99115. if (buffer === void 0) { buffer = null; }
  99116. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99117. var url = String(urlArg);
  99118. texture.url = url;
  99119. texture.generateMipMaps = !noMipmap;
  99120. texture.samplingMode = samplingMode;
  99121. texture.invertY = invertY;
  99122. texture.baseWidth = this._options.textureSize;
  99123. texture.baseHeight = this._options.textureSize;
  99124. texture.width = this._options.textureSize;
  99125. texture.height = this._options.textureSize;
  99126. if (format) {
  99127. texture.format = format;
  99128. }
  99129. texture.isReady = true;
  99130. if (onLoad) {
  99131. onLoad();
  99132. }
  99133. this._internalTexturesCache.push(texture);
  99134. return texture;
  99135. };
  99136. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99137. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99138. if (options !== undefined && typeof options === "object") {
  99139. fullOptions.generateMipMaps = options.generateMipMaps;
  99140. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99141. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99142. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99143. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99144. }
  99145. else {
  99146. fullOptions.generateMipMaps = options;
  99147. fullOptions.generateDepthBuffer = true;
  99148. fullOptions.generateStencilBuffer = false;
  99149. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99150. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99151. }
  99152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99153. var width = size.width || size;
  99154. var height = size.height || size;
  99155. texture._depthStencilBuffer = {};
  99156. texture._framebuffer = {};
  99157. texture.baseWidth = width;
  99158. texture.baseHeight = height;
  99159. texture.width = width;
  99160. texture.height = height;
  99161. texture.isReady = true;
  99162. texture.samples = 1;
  99163. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99164. texture.samplingMode = fullOptions.samplingMode;
  99165. texture.type = fullOptions.type;
  99166. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99167. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99168. this._internalTexturesCache.push(texture);
  99169. return texture;
  99170. };
  99171. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99172. texture.samplingMode = samplingMode;
  99173. };
  99174. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99175. if (this._currentRenderTarget) {
  99176. this.unBindFramebuffer(this._currentRenderTarget);
  99177. }
  99178. this._currentRenderTarget = texture;
  99179. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99180. if (this._cachedViewport && !forceFullscreenViewport) {
  99181. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99182. }
  99183. };
  99184. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99185. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99186. this._currentRenderTarget = null;
  99187. if (onBeforeUnbind) {
  99188. if (texture._MSAAFramebuffer) {
  99189. this._currentFramebuffer = texture._framebuffer;
  99190. }
  99191. onBeforeUnbind();
  99192. }
  99193. this._currentFramebuffer = null;
  99194. };
  99195. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99196. var vbo = {
  99197. capacity: 1,
  99198. references: 1,
  99199. is32Bits: false
  99200. };
  99201. return vbo;
  99202. };
  99203. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99204. if (offset === void 0) { offset = 0; }
  99205. };
  99206. /**
  99207. * Updates a dynamic vertex buffer.
  99208. * @param vertexBuffer the vertex buffer to update
  99209. * @param data the data used to update the vertex buffer
  99210. * @param byteOffset the byte offset of the data (optional)
  99211. * @param byteLength the byte length of the data (optional)
  99212. */
  99213. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99214. };
  99215. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99216. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99217. this._boundTexturesCache[this._activeChannel] = texture;
  99218. return true;
  99219. }
  99220. return false;
  99221. };
  99222. NullEngine.prototype._bindTexture = function (channel, texture) {
  99223. if (channel < 0) {
  99224. return;
  99225. }
  99226. this._bindTextureDirectly(0, texture);
  99227. };
  99228. NullEngine.prototype._releaseBuffer = function (buffer) {
  99229. buffer.references--;
  99230. if (buffer.references === 0) {
  99231. return true;
  99232. }
  99233. return false;
  99234. };
  99235. NullEngine.prototype.releaseEffects = function () {
  99236. };
  99237. return NullEngine;
  99238. }(BABYLON.Engine));
  99239. BABYLON.NullEngine = NullEngine;
  99240. })(BABYLON || (BABYLON = {}));
  99241. //# sourceMappingURL=babylon.nullEngine.js.map
  99242. var BABYLON;
  99243. (function (BABYLON) {
  99244. /**
  99245. * This class can be used to get instrumentation data from a Babylon engine
  99246. */
  99247. var EngineInstrumentation = /** @class */ (function () {
  99248. function EngineInstrumentation(engine) {
  99249. this.engine = engine;
  99250. this._captureGPUFrameTime = false;
  99251. this._gpuFrameTime = new BABYLON.PerfCounter();
  99252. this._captureShaderCompilationTime = false;
  99253. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99254. // Observers
  99255. this._onBeginFrameObserver = null;
  99256. this._onEndFrameObserver = null;
  99257. this._onBeforeShaderCompilationObserver = null;
  99258. this._onAfterShaderCompilationObserver = null;
  99259. }
  99260. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99261. // Properties
  99262. /**
  99263. * Gets the perf counter used for GPU frame time
  99264. */
  99265. get: function () {
  99266. return this._gpuFrameTime;
  99267. },
  99268. enumerable: true,
  99269. configurable: true
  99270. });
  99271. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99272. /**
  99273. * Gets the GPU frame time capture status
  99274. */
  99275. get: function () {
  99276. return this._captureGPUFrameTime;
  99277. },
  99278. /**
  99279. * Enable or disable the GPU frame time capture
  99280. */
  99281. set: function (value) {
  99282. var _this = this;
  99283. if (value === this._captureGPUFrameTime) {
  99284. return;
  99285. }
  99286. this._captureGPUFrameTime = value;
  99287. if (value) {
  99288. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99289. if (!_this._gpuFrameTimeToken) {
  99290. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99291. }
  99292. });
  99293. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99294. if (!_this._gpuFrameTimeToken) {
  99295. return;
  99296. }
  99297. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99298. if (time > -1) {
  99299. _this._gpuFrameTimeToken = null;
  99300. _this._gpuFrameTime.fetchNewFrame();
  99301. _this._gpuFrameTime.addCount(time, true);
  99302. }
  99303. });
  99304. }
  99305. else {
  99306. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99307. this._onBeginFrameObserver = null;
  99308. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99309. this._onEndFrameObserver = null;
  99310. }
  99311. },
  99312. enumerable: true,
  99313. configurable: true
  99314. });
  99315. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99316. /**
  99317. * Gets the perf counter used for shader compilation time
  99318. */
  99319. get: function () {
  99320. return this._shaderCompilationTime;
  99321. },
  99322. enumerable: true,
  99323. configurable: true
  99324. });
  99325. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99326. /**
  99327. * Gets the shader compilation time capture status
  99328. */
  99329. get: function () {
  99330. return this._captureShaderCompilationTime;
  99331. },
  99332. /**
  99333. * Enable or disable the shader compilation time capture
  99334. */
  99335. set: function (value) {
  99336. var _this = this;
  99337. if (value === this._captureShaderCompilationTime) {
  99338. return;
  99339. }
  99340. this._captureShaderCompilationTime = value;
  99341. if (value) {
  99342. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99343. _this._shaderCompilationTime.fetchNewFrame();
  99344. _this._shaderCompilationTime.beginMonitoring();
  99345. });
  99346. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99347. _this._shaderCompilationTime.endMonitoring();
  99348. });
  99349. }
  99350. else {
  99351. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99352. this._onBeforeShaderCompilationObserver = null;
  99353. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99354. this._onAfterShaderCompilationObserver = null;
  99355. }
  99356. },
  99357. enumerable: true,
  99358. configurable: true
  99359. });
  99360. EngineInstrumentation.prototype.dispose = function () {
  99361. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99362. this._onBeginFrameObserver = null;
  99363. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99364. this._onEndFrameObserver = null;
  99365. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99366. this._onBeforeShaderCompilationObserver = null;
  99367. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99368. this._onAfterShaderCompilationObserver = null;
  99369. this.engine = null;
  99370. };
  99371. return EngineInstrumentation;
  99372. }());
  99373. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99374. })(BABYLON || (BABYLON = {}));
  99375. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99376. var BABYLON;
  99377. (function (BABYLON) {
  99378. /**
  99379. * This class can be used to get instrumentation data from a Babylon engine
  99380. */
  99381. var SceneInstrumentation = /** @class */ (function () {
  99382. function SceneInstrumentation(scene) {
  99383. var _this = this;
  99384. this.scene = scene;
  99385. this._captureActiveMeshesEvaluationTime = false;
  99386. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99387. this._captureRenderTargetsRenderTime = false;
  99388. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99389. this._captureFrameTime = false;
  99390. this._frameTime = new BABYLON.PerfCounter();
  99391. this._captureRenderTime = false;
  99392. this._renderTime = new BABYLON.PerfCounter();
  99393. this._captureInterFrameTime = false;
  99394. this._interFrameTime = new BABYLON.PerfCounter();
  99395. this._captureParticlesRenderTime = false;
  99396. this._particlesRenderTime = new BABYLON.PerfCounter();
  99397. this._captureSpritesRenderTime = false;
  99398. this._spritesRenderTime = new BABYLON.PerfCounter();
  99399. this._capturePhysicsTime = false;
  99400. this._physicsTime = new BABYLON.PerfCounter();
  99401. this._captureAnimationsTime = false;
  99402. this._animationsTime = new BABYLON.PerfCounter();
  99403. this._captureCameraRenderTime = false;
  99404. this._cameraRenderTime = new BABYLON.PerfCounter();
  99405. // Observers
  99406. this._onBeforeActiveMeshesEvaluationObserver = null;
  99407. this._onAfterActiveMeshesEvaluationObserver = null;
  99408. this._onBeforeRenderTargetsRenderObserver = null;
  99409. this._onAfterRenderTargetsRenderObserver = null;
  99410. this._onAfterRenderObserver = null;
  99411. this._onBeforeDrawPhaseObserver = null;
  99412. this._onAfterDrawPhaseObserver = null;
  99413. this._onBeforeAnimationsObserver = null;
  99414. this._onBeforeParticlesRenderingObserver = null;
  99415. this._onAfterParticlesRenderingObserver = null;
  99416. this._onBeforeSpritesRenderingObserver = null;
  99417. this._onAfterSpritesRenderingObserver = null;
  99418. this._onBeforePhysicsObserver = null;
  99419. this._onAfterPhysicsObserver = null;
  99420. this._onAfterAnimationsObserver = null;
  99421. this._onBeforeCameraRenderObserver = null;
  99422. this._onAfterCameraRenderObserver = null;
  99423. // Before render
  99424. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99425. if (_this._captureActiveMeshesEvaluationTime) {
  99426. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99427. }
  99428. if (_this._captureRenderTargetsRenderTime) {
  99429. _this._renderTargetsRenderTime.fetchNewFrame();
  99430. }
  99431. if (_this._captureFrameTime) {
  99432. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99433. _this._frameTime.beginMonitoring();
  99434. }
  99435. if (_this._captureInterFrameTime) {
  99436. _this._interFrameTime.endMonitoring();
  99437. }
  99438. if (_this._captureParticlesRenderTime) {
  99439. _this._particlesRenderTime.fetchNewFrame();
  99440. }
  99441. if (_this._captureSpritesRenderTime) {
  99442. _this._spritesRenderTime.fetchNewFrame();
  99443. }
  99444. if (_this._captureAnimationsTime) {
  99445. _this._animationsTime.beginMonitoring();
  99446. }
  99447. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99448. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99449. });
  99450. // After render
  99451. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99452. if (_this._captureFrameTime) {
  99453. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99454. _this._frameTime.endMonitoring();
  99455. }
  99456. if (_this._captureRenderTime) {
  99457. _this._renderTime.endMonitoring(false);
  99458. }
  99459. if (_this._captureInterFrameTime) {
  99460. _this._interFrameTime.beginMonitoring();
  99461. }
  99462. });
  99463. }
  99464. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99465. // Properties
  99466. /**
  99467. * Gets the perf counter used for active meshes evaluation time
  99468. */
  99469. get: function () {
  99470. return this._activeMeshesEvaluationTime;
  99471. },
  99472. enumerable: true,
  99473. configurable: true
  99474. });
  99475. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99476. /**
  99477. * Gets the active meshes evaluation time capture status
  99478. */
  99479. get: function () {
  99480. return this._captureActiveMeshesEvaluationTime;
  99481. },
  99482. /**
  99483. * Enable or disable the active meshes evaluation time capture
  99484. */
  99485. set: function (value) {
  99486. var _this = this;
  99487. if (value === this._captureActiveMeshesEvaluationTime) {
  99488. return;
  99489. }
  99490. this._captureActiveMeshesEvaluationTime = value;
  99491. if (value) {
  99492. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99493. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99494. _this._activeMeshesEvaluationTime.beginMonitoring();
  99495. });
  99496. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99497. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99498. _this._activeMeshesEvaluationTime.endMonitoring();
  99499. });
  99500. }
  99501. else {
  99502. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99503. this._onBeforeActiveMeshesEvaluationObserver = null;
  99504. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99505. this._onAfterActiveMeshesEvaluationObserver = null;
  99506. }
  99507. },
  99508. enumerable: true,
  99509. configurable: true
  99510. });
  99511. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99512. /**
  99513. * Gets the perf counter used for render targets render time
  99514. */
  99515. get: function () {
  99516. return this._renderTargetsRenderTime;
  99517. },
  99518. enumerable: true,
  99519. configurable: true
  99520. });
  99521. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99522. /**
  99523. * Gets the render targets render time capture status
  99524. */
  99525. get: function () {
  99526. return this._captureRenderTargetsRenderTime;
  99527. },
  99528. /**
  99529. * Enable or disable the render targets render time capture
  99530. */
  99531. set: function (value) {
  99532. var _this = this;
  99533. if (value === this._captureRenderTargetsRenderTime) {
  99534. return;
  99535. }
  99536. this._captureRenderTargetsRenderTime = value;
  99537. if (value) {
  99538. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99539. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99540. _this._renderTargetsRenderTime.beginMonitoring();
  99541. });
  99542. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99543. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99544. _this._renderTargetsRenderTime.endMonitoring(false);
  99545. });
  99546. }
  99547. else {
  99548. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99549. this._onBeforeRenderTargetsRenderObserver = null;
  99550. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99551. this._onAfterRenderTargetsRenderObserver = null;
  99552. }
  99553. },
  99554. enumerable: true,
  99555. configurable: true
  99556. });
  99557. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99558. /**
  99559. * Gets the perf counter used for particles render time
  99560. */
  99561. get: function () {
  99562. return this._particlesRenderTime;
  99563. },
  99564. enumerable: true,
  99565. configurable: true
  99566. });
  99567. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99568. /**
  99569. * Gets the particles render time capture status
  99570. */
  99571. get: function () {
  99572. return this._captureParticlesRenderTime;
  99573. },
  99574. /**
  99575. * Enable or disable the particles render time capture
  99576. */
  99577. set: function (value) {
  99578. var _this = this;
  99579. if (value === this._captureParticlesRenderTime) {
  99580. return;
  99581. }
  99582. this._captureParticlesRenderTime = value;
  99583. if (value) {
  99584. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99585. BABYLON.Tools.StartPerformanceCounter("Particles");
  99586. _this._particlesRenderTime.beginMonitoring();
  99587. });
  99588. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99589. BABYLON.Tools.EndPerformanceCounter("Particles");
  99590. _this._particlesRenderTime.endMonitoring(false);
  99591. });
  99592. }
  99593. else {
  99594. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99595. this._onBeforeParticlesRenderingObserver = null;
  99596. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99597. this._onAfterParticlesRenderingObserver = null;
  99598. }
  99599. },
  99600. enumerable: true,
  99601. configurable: true
  99602. });
  99603. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99604. /**
  99605. * Gets the perf counter used for sprites render time
  99606. */
  99607. get: function () {
  99608. return this._spritesRenderTime;
  99609. },
  99610. enumerable: true,
  99611. configurable: true
  99612. });
  99613. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99614. /**
  99615. * Gets the sprites render time capture status
  99616. */
  99617. get: function () {
  99618. return this._captureSpritesRenderTime;
  99619. },
  99620. /**
  99621. * Enable or disable the sprites render time capture
  99622. */
  99623. set: function (value) {
  99624. var _this = this;
  99625. if (value === this._captureSpritesRenderTime) {
  99626. return;
  99627. }
  99628. this._captureSpritesRenderTime = value;
  99629. if (value) {
  99630. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99631. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99632. _this._spritesRenderTime.beginMonitoring();
  99633. });
  99634. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99635. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99636. _this._spritesRenderTime.endMonitoring(false);
  99637. });
  99638. }
  99639. else {
  99640. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99641. this._onBeforeSpritesRenderingObserver = null;
  99642. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99643. this._onAfterSpritesRenderingObserver = null;
  99644. }
  99645. },
  99646. enumerable: true,
  99647. configurable: true
  99648. });
  99649. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99650. /**
  99651. * Gets the perf counter used for physics time
  99652. */
  99653. get: function () {
  99654. return this._physicsTime;
  99655. },
  99656. enumerable: true,
  99657. configurable: true
  99658. });
  99659. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99660. /**
  99661. * Gets the physics time capture status
  99662. */
  99663. get: function () {
  99664. return this._capturePhysicsTime;
  99665. },
  99666. /**
  99667. * Enable or disable the physics time capture
  99668. */
  99669. set: function (value) {
  99670. var _this = this;
  99671. if (value === this._capturePhysicsTime) {
  99672. return;
  99673. }
  99674. this._capturePhysicsTime = value;
  99675. if (value) {
  99676. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99677. BABYLON.Tools.StartPerformanceCounter("Physics");
  99678. _this._physicsTime.beginMonitoring();
  99679. });
  99680. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99681. BABYLON.Tools.EndPerformanceCounter("Physics");
  99682. _this._physicsTime.endMonitoring();
  99683. });
  99684. }
  99685. else {
  99686. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99687. this._onBeforePhysicsObserver = null;
  99688. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99689. this._onAfterPhysicsObserver = null;
  99690. }
  99691. },
  99692. enumerable: true,
  99693. configurable: true
  99694. });
  99695. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99696. /**
  99697. * Gets the perf counter used for animations time
  99698. */
  99699. get: function () {
  99700. return this._animationsTime;
  99701. },
  99702. enumerable: true,
  99703. configurable: true
  99704. });
  99705. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99706. /**
  99707. * Gets the animations time capture status
  99708. */
  99709. get: function () {
  99710. return this._captureAnimationsTime;
  99711. },
  99712. /**
  99713. * Enable or disable the animations time capture
  99714. */
  99715. set: function (value) {
  99716. var _this = this;
  99717. if (value === this._captureAnimationsTime) {
  99718. return;
  99719. }
  99720. this._captureAnimationsTime = value;
  99721. if (value) {
  99722. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99723. _this._animationsTime.endMonitoring();
  99724. });
  99725. }
  99726. else {
  99727. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99728. this._onAfterAnimationsObserver = null;
  99729. }
  99730. },
  99731. enumerable: true,
  99732. configurable: true
  99733. });
  99734. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99735. /**
  99736. * Gets the perf counter used for frame time capture
  99737. */
  99738. get: function () {
  99739. return this._frameTime;
  99740. },
  99741. enumerable: true,
  99742. configurable: true
  99743. });
  99744. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99745. /**
  99746. * Gets the frame time capture status
  99747. */
  99748. get: function () {
  99749. return this._captureFrameTime;
  99750. },
  99751. /**
  99752. * Enable or disable the frame time capture
  99753. */
  99754. set: function (value) {
  99755. this._captureFrameTime = value;
  99756. },
  99757. enumerable: true,
  99758. configurable: true
  99759. });
  99760. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99761. /**
  99762. * Gets the perf counter used for inter-frames time capture
  99763. */
  99764. get: function () {
  99765. return this._interFrameTime;
  99766. },
  99767. enumerable: true,
  99768. configurable: true
  99769. });
  99770. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99771. /**
  99772. * Gets the inter-frames time capture status
  99773. */
  99774. get: function () {
  99775. return this._captureInterFrameTime;
  99776. },
  99777. /**
  99778. * Enable or disable the inter-frames time capture
  99779. */
  99780. set: function (value) {
  99781. this._captureInterFrameTime = value;
  99782. },
  99783. enumerable: true,
  99784. configurable: true
  99785. });
  99786. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99787. /**
  99788. * Gets the perf counter used for render time capture
  99789. */
  99790. get: function () {
  99791. return this._renderTime;
  99792. },
  99793. enumerable: true,
  99794. configurable: true
  99795. });
  99796. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99797. /**
  99798. * Gets the render time capture status
  99799. */
  99800. get: function () {
  99801. return this._captureRenderTime;
  99802. },
  99803. /**
  99804. * Enable or disable the render time capture
  99805. */
  99806. set: function (value) {
  99807. var _this = this;
  99808. if (value === this._captureRenderTime) {
  99809. return;
  99810. }
  99811. this._captureRenderTime = value;
  99812. if (value) {
  99813. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99814. _this._renderTime.beginMonitoring();
  99815. BABYLON.Tools.StartPerformanceCounter("Main render");
  99816. });
  99817. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99818. _this._renderTime.endMonitoring(false);
  99819. BABYLON.Tools.EndPerformanceCounter("Main render");
  99820. });
  99821. }
  99822. else {
  99823. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99824. this._onBeforeDrawPhaseObserver = null;
  99825. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99826. this._onAfterDrawPhaseObserver = null;
  99827. }
  99828. },
  99829. enumerable: true,
  99830. configurable: true
  99831. });
  99832. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99833. /**
  99834. * Gets the perf counter used for camera render time capture
  99835. */
  99836. get: function () {
  99837. return this._cameraRenderTime;
  99838. },
  99839. enumerable: true,
  99840. configurable: true
  99841. });
  99842. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99843. /**
  99844. * Gets the camera render time capture status
  99845. */
  99846. get: function () {
  99847. return this._captureCameraRenderTime;
  99848. },
  99849. /**
  99850. * Enable or disable the camera render time capture
  99851. */
  99852. set: function (value) {
  99853. var _this = this;
  99854. if (value === this._captureCameraRenderTime) {
  99855. return;
  99856. }
  99857. this._captureCameraRenderTime = value;
  99858. if (value) {
  99859. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99860. _this._cameraRenderTime.beginMonitoring();
  99861. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99862. });
  99863. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99864. _this._cameraRenderTime.endMonitoring(false);
  99865. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99866. });
  99867. }
  99868. else {
  99869. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99870. this._onBeforeCameraRenderObserver = null;
  99871. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99872. this._onAfterCameraRenderObserver = null;
  99873. }
  99874. },
  99875. enumerable: true,
  99876. configurable: true
  99877. });
  99878. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99879. /**
  99880. * Gets the perf counter used for draw calls
  99881. */
  99882. get: function () {
  99883. return this.scene.getEngine()._drawCalls;
  99884. },
  99885. enumerable: true,
  99886. configurable: true
  99887. });
  99888. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99889. /**
  99890. * Gets the perf counter used for texture collisions
  99891. */
  99892. get: function () {
  99893. return this.scene.getEngine()._textureCollisions;
  99894. },
  99895. enumerable: true,
  99896. configurable: true
  99897. });
  99898. SceneInstrumentation.prototype.dispose = function () {
  99899. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99900. this._onAfterRenderObserver = null;
  99901. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99902. this._onBeforeActiveMeshesEvaluationObserver = null;
  99903. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99904. this._onAfterActiveMeshesEvaluationObserver = null;
  99905. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99906. this._onBeforeRenderTargetsRenderObserver = null;
  99907. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99908. this._onAfterRenderTargetsRenderObserver = null;
  99909. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99910. this._onBeforeAnimationsObserver = null;
  99911. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99912. this._onBeforeParticlesRenderingObserver = null;
  99913. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99914. this._onAfterParticlesRenderingObserver = null;
  99915. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99916. this._onBeforeSpritesRenderingObserver = null;
  99917. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99918. this._onAfterSpritesRenderingObserver = null;
  99919. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99920. this._onBeforeDrawPhaseObserver = null;
  99921. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99922. this._onAfterDrawPhaseObserver = null;
  99923. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99924. this._onBeforePhysicsObserver = null;
  99925. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99926. this._onAfterPhysicsObserver = null;
  99927. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99928. this._onAfterAnimationsObserver = null;
  99929. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99930. this._onBeforeCameraRenderObserver = null;
  99931. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99932. this._onAfterCameraRenderObserver = null;
  99933. this.scene = null;
  99934. };
  99935. return SceneInstrumentation;
  99936. }());
  99937. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99938. })(BABYLON || (BABYLON = {}));
  99939. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99940. var BABYLON;
  99941. (function (BABYLON) {
  99942. /**
  99943. * @hidden
  99944. **/
  99945. var _TimeToken = /** @class */ (function () {
  99946. function _TimeToken() {
  99947. this._timeElapsedQueryEnded = false;
  99948. }
  99949. return _TimeToken;
  99950. }());
  99951. BABYLON._TimeToken = _TimeToken;
  99952. })(BABYLON || (BABYLON = {}));
  99953. //# sourceMappingURL=babylon.timeToken.js.map
  99954. var BABYLON;
  99955. (function (BABYLON) {
  99956. /**
  99957. * Background material defines definition.
  99958. * @hidden Mainly internal Use
  99959. */
  99960. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99961. __extends(BackgroundMaterialDefines, _super);
  99962. /**
  99963. * Constructor of the defines.
  99964. */
  99965. function BackgroundMaterialDefines() {
  99966. var _this = _super.call(this) || this;
  99967. /**
  99968. * True if the diffuse texture is in use.
  99969. */
  99970. _this.DIFFUSE = false;
  99971. /**
  99972. * The direct UV channel to use.
  99973. */
  99974. _this.DIFFUSEDIRECTUV = 0;
  99975. /**
  99976. * True if the diffuse texture is in gamma space.
  99977. */
  99978. _this.GAMMADIFFUSE = false;
  99979. /**
  99980. * True if the diffuse texture has opacity in the alpha channel.
  99981. */
  99982. _this.DIFFUSEHASALPHA = false;
  99983. /**
  99984. * True if you want the material to fade to transparent at grazing angle.
  99985. */
  99986. _this.OPACITYFRESNEL = false;
  99987. /**
  99988. * True if an extra blur needs to be added in the reflection.
  99989. */
  99990. _this.REFLECTIONBLUR = false;
  99991. /**
  99992. * True if you want the material to fade to reflection at grazing angle.
  99993. */
  99994. _this.REFLECTIONFRESNEL = false;
  99995. /**
  99996. * True if you want the material to falloff as far as you move away from the scene center.
  99997. */
  99998. _this.REFLECTIONFALLOFF = false;
  99999. /**
  100000. * False if the current Webgl implementation does not support the texture lod extension.
  100001. */
  100002. _this.TEXTURELODSUPPORT = false;
  100003. /**
  100004. * True to ensure the data are premultiplied.
  100005. */
  100006. _this.PREMULTIPLYALPHA = false;
  100007. /**
  100008. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100009. */
  100010. _this.USERGBCOLOR = false;
  100011. /**
  100012. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100013. * stays aligned with the desired configuration.
  100014. */
  100015. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100016. /**
  100017. * True to add noise in order to reduce the banding effect.
  100018. */
  100019. _this.NOISE = false;
  100020. /**
  100021. * is the reflection texture in BGR color scheme?
  100022. * Mainly used to solve a bug in ios10 video tag
  100023. */
  100024. _this.REFLECTIONBGR = false;
  100025. _this.IMAGEPROCESSING = false;
  100026. _this.VIGNETTE = false;
  100027. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100028. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100029. _this.TONEMAPPING = false;
  100030. _this.CONTRAST = false;
  100031. _this.COLORCURVES = false;
  100032. _this.COLORGRADING = false;
  100033. _this.COLORGRADING3D = false;
  100034. _this.SAMPLER3DGREENDEPTH = false;
  100035. _this.SAMPLER3DBGRMAP = false;
  100036. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100037. _this.EXPOSURE = false;
  100038. // Reflection.
  100039. _this.REFLECTION = false;
  100040. _this.REFLECTIONMAP_3D = false;
  100041. _this.REFLECTIONMAP_SPHERICAL = false;
  100042. _this.REFLECTIONMAP_PLANAR = false;
  100043. _this.REFLECTIONMAP_CUBIC = false;
  100044. _this.REFLECTIONMAP_PROJECTION = false;
  100045. _this.REFLECTIONMAP_SKYBOX = false;
  100046. _this.REFLECTIONMAP_EXPLICIT = false;
  100047. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100048. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100049. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100050. _this.INVERTCUBICMAP = false;
  100051. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100052. _this.LODINREFLECTIONALPHA = false;
  100053. _this.GAMMAREFLECTION = false;
  100054. _this.RGBDREFLECTION = false;
  100055. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100056. // Default BJS.
  100057. _this.MAINUV1 = false;
  100058. _this.MAINUV2 = false;
  100059. _this.UV1 = false;
  100060. _this.UV2 = false;
  100061. _this.CLIPPLANE = false;
  100062. _this.POINTSIZE = false;
  100063. _this.FOG = false;
  100064. _this.NORMAL = false;
  100065. _this.NUM_BONE_INFLUENCERS = 0;
  100066. _this.BonesPerMesh = 0;
  100067. _this.INSTANCES = false;
  100068. _this.SHADOWFLOAT = false;
  100069. _this.rebuild();
  100070. return _this;
  100071. }
  100072. return BackgroundMaterialDefines;
  100073. }(BABYLON.MaterialDefines));
  100074. /**
  100075. * Background material used to create an efficient environement around your scene.
  100076. */
  100077. var BackgroundMaterial = /** @class */ (function (_super) {
  100078. __extends(BackgroundMaterial, _super);
  100079. /**
  100080. * Instantiates a Background Material in the given scene
  100081. * @param name The friendly name of the material
  100082. * @param scene The scene to add the material to
  100083. */
  100084. function BackgroundMaterial(name, scene) {
  100085. var _this = _super.call(this, name, scene) || this;
  100086. /**
  100087. * Key light Color (multiply against the environement texture)
  100088. */
  100089. _this.primaryColor = BABYLON.Color3.White();
  100090. _this._primaryColorShadowLevel = 0;
  100091. _this._primaryColorHighlightLevel = 0;
  100092. /**
  100093. * Reflection Texture used in the material.
  100094. * Should be author in a specific way for the best result (refer to the documentation).
  100095. */
  100096. _this.reflectionTexture = null;
  100097. /**
  100098. * Reflection Texture level of blur.
  100099. *
  100100. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100101. * texture twice.
  100102. */
  100103. _this.reflectionBlur = 0;
  100104. /**
  100105. * Diffuse Texture used in the material.
  100106. * Should be author in a specific way for the best result (refer to the documentation).
  100107. */
  100108. _this.diffuseTexture = null;
  100109. _this._shadowLights = null;
  100110. /**
  100111. * Specify the list of lights casting shadow on the material.
  100112. * All scene shadow lights will be included if null.
  100113. */
  100114. _this.shadowLights = null;
  100115. /**
  100116. * Helps adjusting the shadow to a softer level if required.
  100117. * 0 means black shadows and 1 means no shadows.
  100118. */
  100119. _this.shadowLevel = 0;
  100120. /**
  100121. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100122. * It is usually zero but might be interesting to modify according to your setup.
  100123. */
  100124. _this.sceneCenter = BABYLON.Vector3.Zero();
  100125. /**
  100126. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100127. * This helps ensuring a nice transition when the camera goes under the ground.
  100128. */
  100129. _this.opacityFresnel = true;
  100130. /**
  100131. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100132. * This helps adding a mirror texture on the ground.
  100133. */
  100134. _this.reflectionFresnel = false;
  100135. /**
  100136. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100137. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100138. */
  100139. _this.reflectionFalloffDistance = 0.0;
  100140. /**
  100141. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100142. */
  100143. _this.reflectionAmount = 1.0;
  100144. /**
  100145. * This specifies the weight of the reflection at grazing angle.
  100146. */
  100147. _this.reflectionReflectance0 = 0.05;
  100148. /**
  100149. * This specifies the weight of the reflection at a perpendicular point of view.
  100150. */
  100151. _this.reflectionReflectance90 = 0.5;
  100152. /**
  100153. * Helps to directly use the maps channels instead of their level.
  100154. */
  100155. _this.useRGBColor = true;
  100156. /**
  100157. * This helps reducing the banding effect that could occur on the background.
  100158. */
  100159. _this.enableNoise = false;
  100160. _this._fovMultiplier = 1.0;
  100161. /**
  100162. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100163. */
  100164. _this.useEquirectangularFOV = false;
  100165. _this._maxSimultaneousLights = 4;
  100166. /**
  100167. * Number of Simultaneous lights allowed on the material.
  100168. */
  100169. _this.maxSimultaneousLights = 4;
  100170. /**
  100171. * Keep track of the image processing observer to allow dispose and replace.
  100172. */
  100173. _this._imageProcessingObserver = null;
  100174. /**
  100175. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100176. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100177. */
  100178. _this.switchToBGR = false;
  100179. // Temp values kept as cache in the material.
  100180. _this._renderTargets = new BABYLON.SmartArray(16);
  100181. _this._reflectionControls = BABYLON.Vector4.Zero();
  100182. _this._white = BABYLON.Color3.White();
  100183. _this._primaryShadowColor = BABYLON.Color3.Black();
  100184. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100185. // Setup the default processing configuration to the scene.
  100186. _this._attachImageProcessingConfiguration(null);
  100187. _this.getRenderTargetTextures = function () {
  100188. _this._renderTargets.reset();
  100189. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100190. _this._renderTargets.push(_this._diffuseTexture);
  100191. }
  100192. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100193. _this._renderTargets.push(_this._reflectionTexture);
  100194. }
  100195. return _this._renderTargets;
  100196. };
  100197. return _this;
  100198. }
  100199. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100200. /**
  100201. * Experimental Internal Use Only.
  100202. *
  100203. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100204. * This acts as a helper to set the primary color to a more "human friendly" value.
  100205. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100206. * output color as close as possible from the chosen value.
  100207. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100208. * part of lighting setup.)
  100209. */
  100210. get: function () {
  100211. return this.__perceptualColor;
  100212. },
  100213. set: function (value) {
  100214. this.__perceptualColor = value;
  100215. this._computePrimaryColorFromPerceptualColor();
  100216. this._markAllSubMeshesAsLightsDirty();
  100217. },
  100218. enumerable: true,
  100219. configurable: true
  100220. });
  100221. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100222. /**
  100223. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100224. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100225. */
  100226. get: function () {
  100227. return this._primaryColorShadowLevel;
  100228. },
  100229. set: function (value) {
  100230. this._primaryColorShadowLevel = value;
  100231. this._computePrimaryColors();
  100232. this._markAllSubMeshesAsLightsDirty();
  100233. },
  100234. enumerable: true,
  100235. configurable: true
  100236. });
  100237. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100238. /**
  100239. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100240. * The primary color is used at the level chosen to define what the white area would look.
  100241. */
  100242. get: function () {
  100243. return this._primaryColorHighlightLevel;
  100244. },
  100245. set: function (value) {
  100246. this._primaryColorHighlightLevel = value;
  100247. this._computePrimaryColors();
  100248. this._markAllSubMeshesAsLightsDirty();
  100249. },
  100250. enumerable: true,
  100251. configurable: true
  100252. });
  100253. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100254. /**
  100255. * Sets the reflection reflectance fresnel values according to the default standard
  100256. * empirically know to work well :-)
  100257. */
  100258. set: function (value) {
  100259. var reflectionWeight = value;
  100260. if (reflectionWeight < 0.5) {
  100261. reflectionWeight = reflectionWeight * 2.0;
  100262. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100263. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100264. }
  100265. else {
  100266. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100267. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100268. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100269. }
  100270. },
  100271. enumerable: true,
  100272. configurable: true
  100273. });
  100274. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100275. /**
  100276. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100277. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100278. * Recommended to be keep at 1.0 except for special cases.
  100279. */
  100280. get: function () {
  100281. return this._fovMultiplier;
  100282. },
  100283. set: function (value) {
  100284. if (isNaN(value)) {
  100285. value = 1.0;
  100286. }
  100287. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100288. },
  100289. enumerable: true,
  100290. configurable: true
  100291. });
  100292. /**
  100293. * Attaches a new image processing configuration to the PBR Material.
  100294. * @param configuration (if null the scene configuration will be use)
  100295. */
  100296. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100297. var _this = this;
  100298. if (configuration === this._imageProcessingConfiguration) {
  100299. return;
  100300. }
  100301. // Detaches observer.
  100302. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100303. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100304. }
  100305. // Pick the scene configuration if needed.
  100306. if (!configuration) {
  100307. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100308. }
  100309. else {
  100310. this._imageProcessingConfiguration = configuration;
  100311. }
  100312. // Attaches observer.
  100313. if (this._imageProcessingConfiguration) {
  100314. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100315. _this._computePrimaryColorFromPerceptualColor();
  100316. _this._markAllSubMeshesAsImageProcessingDirty();
  100317. });
  100318. }
  100319. };
  100320. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100321. /**
  100322. * Gets the image processing configuration used either in this material.
  100323. */
  100324. get: function () {
  100325. return this._imageProcessingConfiguration;
  100326. },
  100327. /**
  100328. * Sets the Default image processing configuration used either in the this material.
  100329. *
  100330. * If sets to null, the scene one is in use.
  100331. */
  100332. set: function (value) {
  100333. this._attachImageProcessingConfiguration(value);
  100334. // Ensure the effect will be rebuilt.
  100335. this._markAllSubMeshesAsTexturesDirty();
  100336. },
  100337. enumerable: true,
  100338. configurable: true
  100339. });
  100340. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100341. /**
  100342. * Gets wether the color curves effect is enabled.
  100343. */
  100344. get: function () {
  100345. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100346. },
  100347. /**
  100348. * Sets wether the color curves effect is enabled.
  100349. */
  100350. set: function (value) {
  100351. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100352. },
  100353. enumerable: true,
  100354. configurable: true
  100355. });
  100356. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100357. /**
  100358. * Gets wether the color grading effect is enabled.
  100359. */
  100360. get: function () {
  100361. return this.imageProcessingConfiguration.colorGradingEnabled;
  100362. },
  100363. /**
  100364. * Gets wether the color grading effect is enabled.
  100365. */
  100366. set: function (value) {
  100367. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100368. },
  100369. enumerable: true,
  100370. configurable: true
  100371. });
  100372. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100373. /**
  100374. * Gets wether tonemapping is enabled or not.
  100375. */
  100376. get: function () {
  100377. return this._imageProcessingConfiguration.toneMappingEnabled;
  100378. },
  100379. /**
  100380. * Sets wether tonemapping is enabled or not
  100381. */
  100382. set: function (value) {
  100383. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100384. },
  100385. enumerable: true,
  100386. configurable: true
  100387. });
  100388. ;
  100389. ;
  100390. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100391. /**
  100392. * The camera exposure used on this material.
  100393. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100394. * This corresponds to a photographic exposure.
  100395. */
  100396. get: function () {
  100397. return this._imageProcessingConfiguration.exposure;
  100398. },
  100399. /**
  100400. * The camera exposure used on this material.
  100401. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100402. * This corresponds to a photographic exposure.
  100403. */
  100404. set: function (value) {
  100405. this._imageProcessingConfiguration.exposure = value;
  100406. },
  100407. enumerable: true,
  100408. configurable: true
  100409. });
  100410. ;
  100411. ;
  100412. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100413. /**
  100414. * Gets The camera contrast used on this material.
  100415. */
  100416. get: function () {
  100417. return this._imageProcessingConfiguration.contrast;
  100418. },
  100419. /**
  100420. * Sets The camera contrast used on this material.
  100421. */
  100422. set: function (value) {
  100423. this._imageProcessingConfiguration.contrast = value;
  100424. },
  100425. enumerable: true,
  100426. configurable: true
  100427. });
  100428. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100429. /**
  100430. * Gets the Color Grading 2D Lookup Texture.
  100431. */
  100432. get: function () {
  100433. return this._imageProcessingConfiguration.colorGradingTexture;
  100434. },
  100435. /**
  100436. * Sets the Color Grading 2D Lookup Texture.
  100437. */
  100438. set: function (value) {
  100439. this.imageProcessingConfiguration.colorGradingTexture = value;
  100440. },
  100441. enumerable: true,
  100442. configurable: true
  100443. });
  100444. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100445. /**
  100446. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100447. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100448. * 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;
  100449. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100450. */
  100451. get: function () {
  100452. return this.imageProcessingConfiguration.colorCurves;
  100453. },
  100454. /**
  100455. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100456. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100457. * 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;
  100458. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100459. */
  100460. set: function (value) {
  100461. this.imageProcessingConfiguration.colorCurves = value;
  100462. },
  100463. enumerable: true,
  100464. configurable: true
  100465. });
  100466. /**
  100467. * The entire material has been created in order to prevent overdraw.
  100468. * @returns false
  100469. */
  100470. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100471. return true;
  100472. };
  100473. /**
  100474. * The entire material has been created in order to prevent overdraw.
  100475. * @returns true if blending is enable
  100476. */
  100477. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100478. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100479. };
  100480. /**
  100481. * Checks wether the material is ready to be rendered for a given mesh.
  100482. * @param mesh The mesh to render
  100483. * @param subMesh The submesh to check against
  100484. * @param useInstances Specify wether or not the material is used with instances
  100485. * @returns true if all the dependencies are ready (Textures, Effects...)
  100486. */
  100487. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100488. var _this = this;
  100489. if (useInstances === void 0) { useInstances = false; }
  100490. if (subMesh.effect && this.isFrozen) {
  100491. if (this._wasPreviouslyReady) {
  100492. return true;
  100493. }
  100494. }
  100495. if (!subMesh._materialDefines) {
  100496. subMesh._materialDefines = new BackgroundMaterialDefines();
  100497. }
  100498. var scene = this.getScene();
  100499. var defines = subMesh._materialDefines;
  100500. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100501. if (defines._renderId === scene.getRenderId()) {
  100502. return true;
  100503. }
  100504. }
  100505. var engine = scene.getEngine();
  100506. // Lights
  100507. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100508. defines._needNormals = true;
  100509. // Textures
  100510. if (defines._areTexturesDirty) {
  100511. defines._needUVs = false;
  100512. if (scene.texturesEnabled) {
  100513. if (scene.getEngine().getCaps().textureLOD) {
  100514. defines.TEXTURELODSUPPORT = true;
  100515. }
  100516. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100517. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100518. return false;
  100519. }
  100520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100521. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100522. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100523. defines.OPACITYFRESNEL = this._opacityFresnel;
  100524. }
  100525. else {
  100526. defines.DIFFUSE = false;
  100527. defines.DIFFUSEHASALPHA = false;
  100528. defines.GAMMADIFFUSE = false;
  100529. defines.OPACITYFRESNEL = false;
  100530. }
  100531. var reflectionTexture = this._reflectionTexture;
  100532. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100533. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100534. return false;
  100535. }
  100536. defines.REFLECTION = true;
  100537. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100538. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100539. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100540. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100541. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100542. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100543. defines.REFLECTIONBGR = this.switchToBGR;
  100544. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100545. defines.INVERTCUBICMAP = true;
  100546. }
  100547. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100548. switch (reflectionTexture.coordinatesMode) {
  100549. case BABYLON.Texture.EXPLICIT_MODE:
  100550. defines.REFLECTIONMAP_EXPLICIT = true;
  100551. break;
  100552. case BABYLON.Texture.PLANAR_MODE:
  100553. defines.REFLECTIONMAP_PLANAR = true;
  100554. break;
  100555. case BABYLON.Texture.PROJECTION_MODE:
  100556. defines.REFLECTIONMAP_PROJECTION = true;
  100557. break;
  100558. case BABYLON.Texture.SKYBOX_MODE:
  100559. defines.REFLECTIONMAP_SKYBOX = true;
  100560. break;
  100561. case BABYLON.Texture.SPHERICAL_MODE:
  100562. defines.REFLECTIONMAP_SPHERICAL = true;
  100563. break;
  100564. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100565. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100566. break;
  100567. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100568. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100569. break;
  100570. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100571. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100572. break;
  100573. case BABYLON.Texture.CUBIC_MODE:
  100574. case BABYLON.Texture.INVCUBIC_MODE:
  100575. default:
  100576. defines.REFLECTIONMAP_CUBIC = true;
  100577. break;
  100578. }
  100579. if (this.reflectionFresnel) {
  100580. defines.REFLECTIONFRESNEL = true;
  100581. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100582. this._reflectionControls.x = this.reflectionAmount;
  100583. this._reflectionControls.y = this.reflectionReflectance0;
  100584. this._reflectionControls.z = this.reflectionReflectance90;
  100585. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100586. }
  100587. else {
  100588. defines.REFLECTIONFRESNEL = false;
  100589. defines.REFLECTIONFALLOFF = false;
  100590. }
  100591. }
  100592. else {
  100593. defines.REFLECTION = false;
  100594. defines.REFLECTIONFRESNEL = false;
  100595. defines.REFLECTIONFALLOFF = false;
  100596. defines.REFLECTIONBLUR = false;
  100597. defines.REFLECTIONMAP_3D = false;
  100598. defines.REFLECTIONMAP_SPHERICAL = false;
  100599. defines.REFLECTIONMAP_PLANAR = false;
  100600. defines.REFLECTIONMAP_CUBIC = false;
  100601. defines.REFLECTIONMAP_PROJECTION = false;
  100602. defines.REFLECTIONMAP_SKYBOX = false;
  100603. defines.REFLECTIONMAP_EXPLICIT = false;
  100604. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100605. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100606. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100607. defines.INVERTCUBICMAP = false;
  100608. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100609. defines.LODINREFLECTIONALPHA = false;
  100610. defines.GAMMAREFLECTION = false;
  100611. defines.RGBDREFLECTION = false;
  100612. }
  100613. }
  100614. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100615. defines.USERGBCOLOR = this._useRGBColor;
  100616. defines.NOISE = this._enableNoise;
  100617. }
  100618. if (defines._areLightsDirty) {
  100619. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100620. }
  100621. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100622. if (!this._imageProcessingConfiguration.isReady()) {
  100623. return false;
  100624. }
  100625. this._imageProcessingConfiguration.prepareDefines(defines);
  100626. }
  100627. // Misc.
  100628. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100629. // Values that need to be evaluated on every frame
  100630. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100631. // Attribs
  100632. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100633. if (mesh) {
  100634. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100635. mesh.createNormals(true);
  100636. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100637. }
  100638. }
  100639. }
  100640. // Get correct effect
  100641. if (defines.isDirty) {
  100642. defines.markAsProcessed();
  100643. scene.resetCachedMaterial();
  100644. // Fallbacks
  100645. var fallbacks = new BABYLON.EffectFallbacks();
  100646. if (defines.FOG) {
  100647. fallbacks.addFallback(0, "FOG");
  100648. }
  100649. if (defines.POINTSIZE) {
  100650. fallbacks.addFallback(1, "POINTSIZE");
  100651. }
  100652. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100653. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100654. fallbacks.addCPUSkinningFallback(0, mesh);
  100655. }
  100656. //Attributes
  100657. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100658. if (defines.NORMAL) {
  100659. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100660. }
  100661. if (defines.UV1) {
  100662. attribs.push(BABYLON.VertexBuffer.UVKind);
  100663. }
  100664. if (defines.UV2) {
  100665. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100666. }
  100667. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100668. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100669. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100670. "vFogInfos", "vFogColor", "pointSize",
  100671. "vClipPlane", "mBones",
  100672. "vPrimaryColor", "vPrimaryColorShadow",
  100673. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100674. "shadowLevel", "alpha",
  100675. "vBackgroundCenter", "vReflectionControl",
  100676. "vDiffuseInfos", "diffuseMatrix",
  100677. ];
  100678. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100679. var uniformBuffers = ["Material", "Scene"];
  100680. if (BABYLON.ImageProcessingConfiguration) {
  100681. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100682. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100683. }
  100684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100685. uniformsNames: uniforms,
  100686. uniformBuffersNames: uniformBuffers,
  100687. samplers: samplers,
  100688. defines: defines,
  100689. maxSimultaneousLights: this._maxSimultaneousLights
  100690. });
  100691. var onCompiled = function (effect) {
  100692. if (_this.onCompiled) {
  100693. _this.onCompiled(effect);
  100694. }
  100695. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100696. };
  100697. var join = defines.toString();
  100698. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100699. attributes: attribs,
  100700. uniformsNames: uniforms,
  100701. uniformBuffersNames: uniformBuffers,
  100702. samplers: samplers,
  100703. defines: join,
  100704. fallbacks: fallbacks,
  100705. onCompiled: onCompiled,
  100706. onError: this.onError,
  100707. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100708. }, engine), defines);
  100709. this.buildUniformLayout();
  100710. }
  100711. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100712. return false;
  100713. }
  100714. defines._renderId = scene.getRenderId();
  100715. this._wasPreviouslyReady = true;
  100716. return true;
  100717. };
  100718. /**
  100719. * Compute the primary color according to the chosen perceptual color.
  100720. */
  100721. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100722. if (!this.__perceptualColor) {
  100723. return;
  100724. }
  100725. this._primaryColor.copyFrom(this.__perceptualColor);
  100726. // Revert gamma space.
  100727. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100728. // Revert image processing configuration.
  100729. if (this._imageProcessingConfiguration) {
  100730. // Revert Exposure.
  100731. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100732. }
  100733. this._computePrimaryColors();
  100734. };
  100735. /**
  100736. * Compute the highlights and shadow colors according to their chosen levels.
  100737. */
  100738. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100739. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100740. return;
  100741. }
  100742. // Find the highlight color based on the configuration.
  100743. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100744. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100745. // Find the shadow color based on the configuration.
  100746. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100747. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100748. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100749. };
  100750. /**
  100751. * Build the uniform buffer used in the material.
  100752. */
  100753. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100754. // Order is important !
  100755. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100756. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100757. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100758. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100759. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100760. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100761. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100762. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100763. this._uniformBuffer.addUniform("pointSize", 1);
  100764. this._uniformBuffer.addUniform("shadowLevel", 1);
  100765. this._uniformBuffer.addUniform("alpha", 1);
  100766. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100767. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100768. this._uniformBuffer.create();
  100769. };
  100770. /**
  100771. * Unbind the material.
  100772. */
  100773. BackgroundMaterial.prototype.unbind = function () {
  100774. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100775. this._uniformBuffer.setTexture("diffuseSampler", null);
  100776. }
  100777. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100778. this._uniformBuffer.setTexture("reflectionSampler", null);
  100779. }
  100780. _super.prototype.unbind.call(this);
  100781. };
  100782. /**
  100783. * Bind only the world matrix to the material.
  100784. * @param world The world matrix to bind.
  100785. */
  100786. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100787. this._activeEffect.setMatrix("world", world);
  100788. };
  100789. /**
  100790. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100791. * @param world The world matrix to bind.
  100792. * @param subMesh The submesh to bind for.
  100793. */
  100794. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100795. var scene = this.getScene();
  100796. var defines = subMesh._materialDefines;
  100797. if (!defines) {
  100798. return;
  100799. }
  100800. var effect = subMesh.effect;
  100801. if (!effect) {
  100802. return;
  100803. }
  100804. this._activeEffect = effect;
  100805. // Matrices
  100806. this.bindOnlyWorldMatrix(world);
  100807. // Bones
  100808. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100809. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100810. if (mustRebind) {
  100811. this._uniformBuffer.bindToEffect(effect, "Material");
  100812. this.bindViewProjection(effect);
  100813. var reflectionTexture = this._reflectionTexture;
  100814. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100815. // Texture uniforms
  100816. if (scene.texturesEnabled) {
  100817. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100818. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100819. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100820. }
  100821. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100822. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100823. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100824. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100825. }
  100826. }
  100827. if (this.shadowLevel > 0) {
  100828. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100829. }
  100830. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100831. // Point size
  100832. if (this.pointsCloud) {
  100833. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100834. }
  100835. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100836. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100837. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100838. }
  100839. else {
  100840. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100841. }
  100842. }
  100843. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100844. // Textures
  100845. if (scene.texturesEnabled) {
  100846. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100847. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100848. }
  100849. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100850. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100851. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100852. }
  100853. else if (!defines.REFLECTIONBLUR) {
  100854. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100855. }
  100856. else {
  100857. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100858. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100859. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100860. }
  100861. if (defines.REFLECTIONFRESNEL) {
  100862. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100863. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100864. }
  100865. }
  100866. }
  100867. // Clip plane
  100868. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100869. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100870. }
  100871. if (mustRebind || !this.isFrozen) {
  100872. if (scene.lightsEnabled) {
  100873. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100874. }
  100875. // View
  100876. this.bindView(effect);
  100877. // Fog
  100878. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100879. // image processing
  100880. if (this._imageProcessingConfiguration) {
  100881. this._imageProcessingConfiguration.bind(this._activeEffect);
  100882. }
  100883. }
  100884. this._uniformBuffer.update();
  100885. this._afterBind(mesh, this._activeEffect);
  100886. };
  100887. /**
  100888. * Dispose the material.
  100889. * @param forceDisposeEffect Force disposal of the associated effect.
  100890. * @param forceDisposeTextures Force disposal of the associated textures.
  100891. */
  100892. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100893. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100894. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100895. if (forceDisposeTextures) {
  100896. if (this.diffuseTexture) {
  100897. this.diffuseTexture.dispose();
  100898. }
  100899. if (this.reflectionTexture) {
  100900. this.reflectionTexture.dispose();
  100901. }
  100902. }
  100903. this._renderTargets.dispose();
  100904. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100905. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100906. }
  100907. _super.prototype.dispose.call(this, forceDisposeEffect);
  100908. };
  100909. /**
  100910. * Clones the material.
  100911. * @param name The cloned name.
  100912. * @returns The cloned material.
  100913. */
  100914. BackgroundMaterial.prototype.clone = function (name) {
  100915. var _this = this;
  100916. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100917. };
  100918. /**
  100919. * Serializes the current material to its JSON representation.
  100920. * @returns The JSON representation.
  100921. */
  100922. BackgroundMaterial.prototype.serialize = function () {
  100923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100924. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100925. return serializationObject;
  100926. };
  100927. /**
  100928. * Gets the class name of the material
  100929. * @returns "BackgroundMaterial"
  100930. */
  100931. BackgroundMaterial.prototype.getClassName = function () {
  100932. return "BackgroundMaterial";
  100933. };
  100934. /**
  100935. * Parse a JSON input to create back a background material.
  100936. * @param source The JSON data to parse
  100937. * @param scene The scene to create the parsed material in
  100938. * @param rootUrl The root url of the assets the material depends upon
  100939. * @returns the instantiated BackgroundMaterial.
  100940. */
  100941. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100942. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100943. };
  100944. /**
  100945. * Standard reflectance value at parallel view angle.
  100946. */
  100947. BackgroundMaterial.StandardReflectance0 = 0.05;
  100948. /**
  100949. * Standard reflectance value at grazing angle.
  100950. */
  100951. BackgroundMaterial.StandardReflectance90 = 0.5;
  100952. __decorate([
  100953. BABYLON.serializeAsColor3()
  100954. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100955. __decorate([
  100956. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100957. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100958. __decorate([
  100959. BABYLON.serializeAsColor3()
  100960. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100961. __decorate([
  100962. BABYLON.serialize()
  100963. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100964. __decorate([
  100965. BABYLON.serialize()
  100966. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100967. __decorate([
  100968. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100969. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100970. __decorate([
  100971. BABYLON.serializeAsTexture()
  100972. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100973. __decorate([
  100974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100975. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100976. __decorate([
  100977. BABYLON.serialize()
  100978. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100979. __decorate([
  100980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100981. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100982. __decorate([
  100983. BABYLON.serializeAsTexture()
  100984. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100985. __decorate([
  100986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100987. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100988. __decorate([
  100989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100990. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100991. __decorate([
  100992. BABYLON.serialize()
  100993. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100994. __decorate([
  100995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100996. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100997. __decorate([
  100998. BABYLON.serializeAsVector3()
  100999. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101000. __decorate([
  101001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101002. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101003. __decorate([
  101004. BABYLON.serialize()
  101005. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101006. __decorate([
  101007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101008. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101009. __decorate([
  101010. BABYLON.serialize()
  101011. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101012. __decorate([
  101013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101014. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101015. __decorate([
  101016. BABYLON.serialize()
  101017. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101018. __decorate([
  101019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101020. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101021. __decorate([
  101022. BABYLON.serialize()
  101023. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101024. __decorate([
  101025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101026. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101027. __decorate([
  101028. BABYLON.serialize()
  101029. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101030. __decorate([
  101031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101032. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101033. __decorate([
  101034. BABYLON.serialize()
  101035. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101036. __decorate([
  101037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101038. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101039. __decorate([
  101040. BABYLON.serialize()
  101041. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101042. __decorate([
  101043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101044. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101045. __decorate([
  101046. BABYLON.serialize()
  101047. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101048. __decorate([
  101049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101050. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101051. __decorate([
  101052. BABYLON.serialize()
  101053. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101054. __decorate([
  101055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101056. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101057. __decorate([
  101058. BABYLON.serializeAsImageProcessingConfiguration()
  101059. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101060. return BackgroundMaterial;
  101061. }(BABYLON.PushMaterial));
  101062. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101063. })(BABYLON || (BABYLON = {}));
  101064. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101065. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101066. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101067. s = arguments[i];
  101068. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101069. t[p] = s[p];
  101070. }
  101071. return t;
  101072. };
  101073. var BABYLON;
  101074. (function (BABYLON) {
  101075. /**
  101076. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101077. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101078. * It also helps with the default setup of your imageProcessing configuration.
  101079. */
  101080. var EnvironmentHelper = /** @class */ (function () {
  101081. /**
  101082. * constructor
  101083. * @param options
  101084. * @param scene The scene to add the material to
  101085. */
  101086. function EnvironmentHelper(options, scene) {
  101087. var _this = this;
  101088. this._errorHandler = function (message, exception) {
  101089. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101090. };
  101091. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101092. this._scene = scene;
  101093. this.onErrorObservable = new BABYLON.Observable();
  101094. this._setupBackground();
  101095. this._setupImageProcessing();
  101096. }
  101097. /**
  101098. * Creates the default options for the helper.
  101099. */
  101100. EnvironmentHelper._getDefaultOptions = function () {
  101101. return {
  101102. createGround: true,
  101103. groundSize: 15,
  101104. groundTexture: this._groundTextureCDNUrl,
  101105. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101106. groundOpacity: 0.9,
  101107. enableGroundShadow: true,
  101108. groundShadowLevel: 0.5,
  101109. enableGroundMirror: false,
  101110. groundMirrorSizeRatio: 0.3,
  101111. groundMirrorBlurKernel: 64,
  101112. groundMirrorAmount: 1,
  101113. groundMirrorFresnelWeight: 1,
  101114. groundMirrorFallOffDistance: 0,
  101115. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101116. groundYBias: 0.00001,
  101117. createSkybox: true,
  101118. skyboxSize: 20,
  101119. skyboxTexture: this._skyboxTextureCDNUrl,
  101120. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101121. backgroundYRotation: 0,
  101122. sizeAuto: true,
  101123. rootPosition: BABYLON.Vector3.Zero(),
  101124. setupImageProcessing: true,
  101125. environmentTexture: this._environmentTextureCDNUrl,
  101126. cameraExposure: 0.8,
  101127. cameraContrast: 1.2,
  101128. toneMappingEnabled: true,
  101129. };
  101130. };
  101131. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101132. /**
  101133. * Gets the root mesh created by the helper.
  101134. */
  101135. get: function () {
  101136. return this._rootMesh;
  101137. },
  101138. enumerable: true,
  101139. configurable: true
  101140. });
  101141. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101142. /**
  101143. * Gets the skybox created by the helper.
  101144. */
  101145. get: function () {
  101146. return this._skybox;
  101147. },
  101148. enumerable: true,
  101149. configurable: true
  101150. });
  101151. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101152. /**
  101153. * Gets the skybox texture created by the helper.
  101154. */
  101155. get: function () {
  101156. return this._skyboxTexture;
  101157. },
  101158. enumerable: true,
  101159. configurable: true
  101160. });
  101161. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101162. /**
  101163. * Gets the skybox material created by the helper.
  101164. */
  101165. get: function () {
  101166. return this._skyboxMaterial;
  101167. },
  101168. enumerable: true,
  101169. configurable: true
  101170. });
  101171. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101172. /**
  101173. * Gets the ground mesh created by the helper.
  101174. */
  101175. get: function () {
  101176. return this._ground;
  101177. },
  101178. enumerable: true,
  101179. configurable: true
  101180. });
  101181. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101182. /**
  101183. * Gets the ground texture created by the helper.
  101184. */
  101185. get: function () {
  101186. return this._groundTexture;
  101187. },
  101188. enumerable: true,
  101189. configurable: true
  101190. });
  101191. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101192. /**
  101193. * Gets the ground mirror created by the helper.
  101194. */
  101195. get: function () {
  101196. return this._groundMirror;
  101197. },
  101198. enumerable: true,
  101199. configurable: true
  101200. });
  101201. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101202. /**
  101203. * Gets the ground mirror render list to helps pushing the meshes
  101204. * you wish in the ground reflection.
  101205. */
  101206. get: function () {
  101207. if (this._groundMirror) {
  101208. return this._groundMirror.renderList;
  101209. }
  101210. return null;
  101211. },
  101212. enumerable: true,
  101213. configurable: true
  101214. });
  101215. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101216. /**
  101217. * Gets the ground material created by the helper.
  101218. */
  101219. get: function () {
  101220. return this._groundMaterial;
  101221. },
  101222. enumerable: true,
  101223. configurable: true
  101224. });
  101225. /**
  101226. * Updates the background according to the new options
  101227. * @param options
  101228. */
  101229. EnvironmentHelper.prototype.updateOptions = function (options) {
  101230. var newOptions = __assign({}, this._options, options);
  101231. if (this._ground && !newOptions.createGround) {
  101232. this._ground.dispose();
  101233. this._ground = null;
  101234. }
  101235. if (this._groundMaterial && !newOptions.createGround) {
  101236. this._groundMaterial.dispose();
  101237. this._groundMaterial = null;
  101238. }
  101239. if (this._groundTexture) {
  101240. if (this._options.groundTexture != newOptions.groundTexture) {
  101241. this._groundTexture.dispose();
  101242. this._groundTexture = null;
  101243. }
  101244. }
  101245. if (this._skybox && !newOptions.createSkybox) {
  101246. this._skybox.dispose();
  101247. this._skybox = null;
  101248. }
  101249. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101250. this._skyboxMaterial.dispose();
  101251. this._skyboxMaterial = null;
  101252. }
  101253. if (this._skyboxTexture) {
  101254. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101255. this._skyboxTexture.dispose();
  101256. this._skyboxTexture = null;
  101257. }
  101258. }
  101259. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101260. this._groundMirror.dispose();
  101261. this._groundMirror = null;
  101262. }
  101263. if (this._scene.environmentTexture) {
  101264. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101265. this._scene.environmentTexture.dispose();
  101266. }
  101267. }
  101268. this._options = newOptions;
  101269. this._setupBackground();
  101270. this._setupImageProcessing();
  101271. };
  101272. /**
  101273. * Sets the primary color of all the available elements.
  101274. * @param color the main color to affect to the ground and the background
  101275. */
  101276. EnvironmentHelper.prototype.setMainColor = function (color) {
  101277. if (this.groundMaterial) {
  101278. this.groundMaterial.primaryColor = color;
  101279. }
  101280. if (this.skyboxMaterial) {
  101281. this.skyboxMaterial.primaryColor = color;
  101282. }
  101283. if (this.groundMirror) {
  101284. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101285. }
  101286. };
  101287. /**
  101288. * Setup the image processing according to the specified options.
  101289. */
  101290. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101291. if (this._options.setupImageProcessing) {
  101292. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101293. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101294. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101295. this._setupEnvironmentTexture();
  101296. }
  101297. };
  101298. /**
  101299. * Setup the environment texture according to the specified options.
  101300. */
  101301. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101302. if (this._scene.environmentTexture) {
  101303. return;
  101304. }
  101305. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101306. this._scene.environmentTexture = this._options.environmentTexture;
  101307. return;
  101308. }
  101309. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101310. this._scene.environmentTexture = environmentTexture;
  101311. };
  101312. /**
  101313. * Setup the background according to the specified options.
  101314. */
  101315. EnvironmentHelper.prototype._setupBackground = function () {
  101316. if (!this._rootMesh) {
  101317. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101318. }
  101319. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101320. var sceneSize = this._getSceneSize();
  101321. if (this._options.createGround) {
  101322. this._setupGround(sceneSize);
  101323. this._setupGroundMaterial();
  101324. this._setupGroundDiffuseTexture();
  101325. if (this._options.enableGroundMirror) {
  101326. this._setupGroundMirrorTexture(sceneSize);
  101327. }
  101328. this._setupMirrorInGroundMaterial();
  101329. }
  101330. if (this._options.createSkybox) {
  101331. this._setupSkybox(sceneSize);
  101332. this._setupSkyboxMaterial();
  101333. this._setupSkyboxReflectionTexture();
  101334. }
  101335. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101336. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101337. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101338. };
  101339. /**
  101340. * Get the scene sizes according to the setup.
  101341. */
  101342. EnvironmentHelper.prototype._getSceneSize = function () {
  101343. var _this = this;
  101344. var groundSize = this._options.groundSize;
  101345. var skyboxSize = this._options.skyboxSize;
  101346. var rootPosition = this._options.rootPosition;
  101347. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101348. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101349. }
  101350. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101351. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101352. });
  101353. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101354. if (this._options.sizeAuto) {
  101355. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101356. this._scene.activeCamera.upperRadiusLimit) {
  101357. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101358. skyboxSize = groundSize;
  101359. }
  101360. var sceneDiagonalLenght = sceneDiagonal.length();
  101361. if (sceneDiagonalLenght > groundSize) {
  101362. groundSize = sceneDiagonalLenght * 2;
  101363. skyboxSize = groundSize;
  101364. }
  101365. // 10 % bigger.
  101366. groundSize *= 1.1;
  101367. skyboxSize *= 1.5;
  101368. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101369. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101370. }
  101371. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101372. };
  101373. /**
  101374. * Setup the ground according to the specified options.
  101375. */
  101376. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101377. var _this = this;
  101378. if (!this._ground || this._ground.isDisposed()) {
  101379. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101380. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101381. this._ground.parent = this._rootMesh;
  101382. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101383. }
  101384. this._ground.receiveShadows = this._options.enableGroundShadow;
  101385. };
  101386. /**
  101387. * Setup the ground material according to the specified options.
  101388. */
  101389. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101390. if (!this._groundMaterial) {
  101391. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101392. }
  101393. this._groundMaterial.alpha = this._options.groundOpacity;
  101394. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101395. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101396. this._groundMaterial.primaryColor = this._options.groundColor;
  101397. this._groundMaterial.useRGBColor = false;
  101398. this._groundMaterial.enableNoise = true;
  101399. if (this._ground) {
  101400. this._ground.material = this._groundMaterial;
  101401. }
  101402. };
  101403. /**
  101404. * Setup the ground diffuse texture according to the specified options.
  101405. */
  101406. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101407. if (!this._groundMaterial) {
  101408. return;
  101409. }
  101410. if (this._groundTexture) {
  101411. return;
  101412. }
  101413. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101414. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101415. return;
  101416. }
  101417. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101418. diffuseTexture.gammaSpace = false;
  101419. diffuseTexture.hasAlpha = true;
  101420. this._groundMaterial.diffuseTexture = diffuseTexture;
  101421. };
  101422. /**
  101423. * Setup the ground mirror texture according to the specified options.
  101424. */
  101425. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101426. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101427. if (!this._groundMirror) {
  101428. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101429. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101430. this._groundMirror.anisotropicFilteringLevel = 1;
  101431. this._groundMirror.wrapU = wrapping;
  101432. this._groundMirror.wrapV = wrapping;
  101433. this._groundMirror.gammaSpace = false;
  101434. if (this._groundMirror.renderList) {
  101435. for (var i = 0; i < this._scene.meshes.length; i++) {
  101436. var mesh = this._scene.meshes[i];
  101437. if (mesh !== this._ground &&
  101438. mesh !== this._skybox &&
  101439. mesh !== this._rootMesh) {
  101440. this._groundMirror.renderList.push(mesh);
  101441. }
  101442. }
  101443. }
  101444. }
  101445. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101446. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101447. };
  101448. /**
  101449. * Setup the ground to receive the mirror texture.
  101450. */
  101451. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101452. if (this._groundMaterial) {
  101453. this._groundMaterial.reflectionTexture = this._groundMirror;
  101454. this._groundMaterial.reflectionFresnel = true;
  101455. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101456. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101457. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101458. }
  101459. };
  101460. /**
  101461. * Setup the skybox according to the specified options.
  101462. */
  101463. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101464. var _this = this;
  101465. if (!this._skybox || this._skybox.isDisposed()) {
  101466. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101467. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101468. }
  101469. this._skybox.parent = this._rootMesh;
  101470. };
  101471. /**
  101472. * Setup the skybox material according to the specified options.
  101473. */
  101474. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101475. if (!this._skybox) {
  101476. return;
  101477. }
  101478. if (!this._skyboxMaterial) {
  101479. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101480. }
  101481. this._skyboxMaterial.useRGBColor = false;
  101482. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101483. this._skyboxMaterial.enableNoise = true;
  101484. this._skybox.material = this._skyboxMaterial;
  101485. };
  101486. /**
  101487. * Setup the skybox reflection texture according to the specified options.
  101488. */
  101489. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101490. if (!this._skyboxMaterial) {
  101491. return;
  101492. }
  101493. if (this._skyboxTexture) {
  101494. return;
  101495. }
  101496. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101497. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101498. return;
  101499. }
  101500. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101501. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101502. this._skyboxTexture.gammaSpace = false;
  101503. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101504. };
  101505. /**
  101506. * Dispose all the elements created by the Helper.
  101507. */
  101508. EnvironmentHelper.prototype.dispose = function () {
  101509. if (this._groundMaterial) {
  101510. this._groundMaterial.dispose(true, true);
  101511. }
  101512. if (this._skyboxMaterial) {
  101513. this._skyboxMaterial.dispose(true, true);
  101514. }
  101515. this._rootMesh.dispose(false);
  101516. };
  101517. /**
  101518. * Default ground texture URL.
  101519. */
  101520. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101521. /**
  101522. * Default skybox texture URL.
  101523. */
  101524. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101525. /**
  101526. * Default environment texture URL.
  101527. */
  101528. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101529. return EnvironmentHelper;
  101530. }());
  101531. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101532. })(BABYLON || (BABYLON = {}));
  101533. //# sourceMappingURL=babylon.environmentHelper.js.map
  101534. var BABYLON;
  101535. (function (BABYLON) {
  101536. /**
  101537. * This class is made for on one-liner static method to help creating particle systems.
  101538. */
  101539. var ParticleHelper = /** @class */ (function () {
  101540. function ParticleHelper() {
  101541. }
  101542. /**
  101543. * This is the main static method (one-liner) of this helper to create different particle systems.
  101544. * @param type This string represents the type to the particle system to create
  101545. * @param emitter The object where the particle system will start to emit from.
  101546. * @param scene The scene where the particle system should live.
  101547. * @param gpu If the system will use gpu.
  101548. * @returns the ParticleSystem created.
  101549. */
  101550. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101551. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101552. if (gpu === void 0) { gpu = false; }
  101553. return new Promise(function (resolve, reject) {
  101554. if (!scene) {
  101555. scene = BABYLON.Engine.LastCreatedScene;
  101556. ;
  101557. }
  101558. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101559. return reject("Particle system with GPU is not supported.");
  101560. }
  101561. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101562. var newData = JSON.parse(data.toString());
  101563. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101564. }, undefined, undefined, undefined, function (req, exception) {
  101565. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101566. });
  101567. });
  101568. };
  101569. /**
  101570. * Static function used to create a new particle system from a IParticleSystemData
  101571. * @param data defines the source data
  101572. * @param scene defines the hosting scene
  101573. * @param emitter defines the particle emitter
  101574. * @returns a new ParticleSystem based on referenced data
  101575. */
  101576. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101577. // Create a particle system
  101578. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101579. // Where the particles come from
  101580. system.emitter = emitter; // the starting object, the emitter
  101581. ParticleHelper.UpdateSystem(system, data, scene);
  101582. return system;
  101583. };
  101584. /**
  101585. * Static function used to update a particle system from a IParticleSystemData
  101586. * @param system defines the particle system to update
  101587. * @param data defines the source data
  101588. * @param scene defines the hosting scene
  101589. */
  101590. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101591. // Texture of each particle
  101592. if (data.textureFile) {
  101593. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101594. }
  101595. // Colors of all particles
  101596. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101597. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101598. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101599. // Size of each particle (random between...
  101600. system.minSize = data.minSize;
  101601. system.maxSize = data.maxSize;
  101602. system.minScaleX = data.minScaleX;
  101603. system.maxScaleX = data.maxScaleX;
  101604. system.minScaleY = data.minScaleY;
  101605. system.maxScaleY = data.maxScaleY;
  101606. // Life time of each particle (random between...
  101607. system.minLifeTime = data.minLifeTime;
  101608. system.maxLifeTime = data.maxLifeTime;
  101609. // Emission rate
  101610. system.emitRate = data.emitRate;
  101611. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101612. system.blendMode = data.blendMode;
  101613. // Set the gravity of all particles
  101614. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101615. // Angular speed, in radians
  101616. system.minAngularSpeed = data.minAngularSpeed;
  101617. system.maxAngularSpeed = data.maxAngularSpeed;
  101618. // Speed
  101619. system.minEmitPower = data.minEmitPower;
  101620. system.maxEmitPower = data.maxEmitPower;
  101621. system.updateSpeed = data.updateSpeed;
  101622. switch (data.emitterType) {
  101623. case "box":
  101624. if (!data.direction1 || !data.direction2) {
  101625. throw new Error("Directions are missing in this particle system.");
  101626. }
  101627. if (!data.minEmitBox || !data.maxEmitBox) {
  101628. throw new Error("EmitBox is missing in this particle system.");
  101629. }
  101630. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101631. break;
  101632. case "sphere":
  101633. system.createSphereEmitter(data.radius);
  101634. break;
  101635. case "directed_sphere":
  101636. if (!data.direction1 || !data.direction2) {
  101637. throw new Error("Directions are missing in this particle system.");
  101638. }
  101639. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101640. break;
  101641. case "cone":
  101642. system.createConeEmitter(data.radius, data.angle);
  101643. break;
  101644. default:
  101645. break;
  101646. }
  101647. };
  101648. /**
  101649. * Static function used to export a particle system to a IParticleSystemData variable.
  101650. * Please note that texture file name is not exported and must be added manually
  101651. * @param system defines the particle system to export
  101652. */
  101653. ParticleHelper.ExportSystem = function (system) {
  101654. var outData = {};
  101655. // Colors of all particles
  101656. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101657. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101658. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101659. // Size of each particle (random between...
  101660. outData.minSize = system.minSize;
  101661. outData.maxSize = system.maxSize;
  101662. outData.minScaleX = system.minScaleX;
  101663. outData.maxScaleX = system.maxScaleX;
  101664. outData.minScaleY = system.minScaleY;
  101665. outData.maxScaleY = system.maxScaleY;
  101666. // Life time of each particle (random between...
  101667. outData.minLifeTime = system.minLifeTime;
  101668. outData.maxLifeTime = system.maxLifeTime;
  101669. // Emission rate
  101670. outData.emitRate = system.emitRate;
  101671. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101672. outData.blendMode = system.blendMode;
  101673. // Set the gravity of all particles
  101674. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101675. // Angular speed, in radians
  101676. outData.minAngularSpeed = system.minAngularSpeed;
  101677. outData.maxAngularSpeed = system.maxAngularSpeed;
  101678. // Speed
  101679. outData.minEmitPower = system.minEmitPower;
  101680. outData.maxEmitPower = system.maxEmitPower;
  101681. outData.updateSpeed = system.updateSpeed;
  101682. switch (system.particleEmitterType.getClassName()) {
  101683. case "BoxEmitter":
  101684. outData.emitterType = "box";
  101685. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101686. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101687. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101688. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101689. break;
  101690. case "SphereParticleEmitter":
  101691. outData.emitterType = "sphere";
  101692. outData.radius = system.particleEmitterType.radius;
  101693. break;
  101694. case "SphereDirectedParticleEmitter":
  101695. outData.emitterType = "directed_sphere";
  101696. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101697. outData.radius = sphereDirectedParticleEmitter.radius;
  101698. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101699. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101700. break;
  101701. case "ConeEmitter":
  101702. outData.emitterType = "cone";
  101703. outData.radius = system.particleEmitterType.radius;
  101704. outData.angle = system.particleEmitterType.angle;
  101705. break;
  101706. default:
  101707. break;
  101708. }
  101709. return outData;
  101710. };
  101711. /**
  101712. * Base Assets URL.
  101713. */
  101714. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101715. return ParticleHelper;
  101716. }());
  101717. BABYLON.ParticleHelper = ParticleHelper;
  101718. })(BABYLON || (BABYLON = {}));
  101719. //# sourceMappingURL=babylon.particleHelper.js.map
  101720. var BABYLON;
  101721. (function (BABYLON) {
  101722. /**
  101723. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101724. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101725. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101726. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101727. */
  101728. var VideoDome = /** @class */ (function (_super) {
  101729. __extends(VideoDome, _super);
  101730. /**
  101731. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101732. * @param name Element's name, child elements will append suffixes for their own names.
  101733. * @param urlsOrVideo defines the url(s) or the video element to use
  101734. * @param options An object containing optional or exposed sub element properties
  101735. */
  101736. function VideoDome(name, urlsOrVideo, options, scene) {
  101737. var _this = _super.call(this, name, scene) || this;
  101738. _this._useDirectMapping = false;
  101739. // set defaults and manage values
  101740. name = name || "videoDome";
  101741. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101742. options.clickToPlay = Boolean(options.clickToPlay);
  101743. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101744. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101745. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101746. if (options.useDirectMapping === undefined) {
  101747. _this._useDirectMapping = true;
  101748. }
  101749. else {
  101750. _this._useDirectMapping = options.useDirectMapping;
  101751. }
  101752. // create
  101753. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101754. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101755. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101756. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101757. // configure material
  101758. material.useEquirectangularFOV = true;
  101759. material.fovMultiplier = 1.0;
  101760. material.opacityFresnel = false;
  101761. if (_this._useDirectMapping) {
  101762. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101763. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101764. material.diffuseTexture = texture;
  101765. }
  101766. else {
  101767. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101768. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101769. material.reflectionTexture = texture;
  101770. }
  101771. // configure mesh
  101772. _this._mesh.material = material;
  101773. _this._mesh.parent = _this;
  101774. // optional configuration
  101775. if (options.clickToPlay) {
  101776. scene.onPointerUp = function () {
  101777. _this._videoTexture.video.play();
  101778. };
  101779. }
  101780. return _this;
  101781. }
  101782. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101783. /**
  101784. * Gets the video texture being displayed on the sphere
  101785. */
  101786. get: function () {
  101787. return this._videoTexture;
  101788. },
  101789. enumerable: true,
  101790. configurable: true
  101791. });
  101792. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101793. /**
  101794. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101795. * Also see the options.resolution property.
  101796. */
  101797. get: function () {
  101798. return this._material.fovMultiplier;
  101799. },
  101800. set: function (value) {
  101801. this._material.fovMultiplier = value;
  101802. },
  101803. enumerable: true,
  101804. configurable: true
  101805. });
  101806. /**
  101807. * Releases resources associated with this node.
  101808. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101809. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101810. */
  101811. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101812. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101813. this._videoTexture.dispose();
  101814. this._mesh.dispose();
  101815. this._material.dispose();
  101816. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101817. };
  101818. return VideoDome;
  101819. }(BABYLON.Node));
  101820. BABYLON.VideoDome = VideoDome;
  101821. })(BABYLON || (BABYLON = {}));
  101822. //# sourceMappingURL=babylon.videoDome.js.map
  101823. var BABYLON;
  101824. (function (BABYLON) {
  101825. /**
  101826. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101827. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101828. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101829. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101830. */
  101831. var PhotoDome = /** @class */ (function (_super) {
  101832. __extends(PhotoDome, _super);
  101833. /**
  101834. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101835. * @param name Element's name, child elements will append suffixes for their own names.
  101836. * @param urlsOfPhoto define the url of the photo to display
  101837. * @param options An object containing optional or exposed sub element properties
  101838. */
  101839. function PhotoDome(name, urlOfPhoto, options, scene) {
  101840. var _this = _super.call(this, name, scene) || this;
  101841. _this._useDirectMapping = false;
  101842. // set defaults and manage values
  101843. name = name || "photoDome";
  101844. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101845. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101846. if (options.useDirectMapping === undefined) {
  101847. _this._useDirectMapping = true;
  101848. }
  101849. else {
  101850. _this._useDirectMapping = options.useDirectMapping;
  101851. }
  101852. // create
  101853. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101854. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101855. // configure material
  101856. material.opacityFresnel = false;
  101857. material.useEquirectangularFOV = true;
  101858. material.fovMultiplier = 1.0;
  101859. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  101860. // configure mesh
  101861. _this._mesh.material = material;
  101862. _this._mesh.parent = _this;
  101863. return _this;
  101864. }
  101865. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101866. /**
  101867. * Gets or sets the texture being displayed on the sphere
  101868. */
  101869. get: function () {
  101870. return this._photoTexture;
  101871. },
  101872. set: function (value) {
  101873. if (this._photoTexture === value) {
  101874. return;
  101875. }
  101876. this._photoTexture = value;
  101877. if (this._useDirectMapping) {
  101878. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101879. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101880. this._material.diffuseTexture = this._photoTexture;
  101881. }
  101882. else {
  101883. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101884. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101885. this._material.reflectionTexture = this._photoTexture;
  101886. }
  101887. },
  101888. enumerable: true,
  101889. configurable: true
  101890. });
  101891. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101892. /**
  101893. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101894. * Also see the options.resolution property.
  101895. */
  101896. get: function () {
  101897. return this._material.fovMultiplier;
  101898. },
  101899. set: function (value) {
  101900. this._material.fovMultiplier = value;
  101901. },
  101902. enumerable: true,
  101903. configurable: true
  101904. });
  101905. /**
  101906. * Releases resources associated with this node.
  101907. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101908. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101909. */
  101910. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101911. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101912. this._photoTexture.dispose();
  101913. this._mesh.dispose();
  101914. this._material.dispose();
  101915. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101916. };
  101917. return PhotoDome;
  101918. }(BABYLON.Node));
  101919. BABYLON.PhotoDome = PhotoDome;
  101920. })(BABYLON || (BABYLON = {}));
  101921. //# sourceMappingURL=babylon.photoDome.js.map
  101922. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#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\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || 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;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \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 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;\nvec3 worldPos=position+alignedCorner; \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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\nvoid main() {\nvUV=uv;\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*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\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;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform 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 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 CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float 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\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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"};
  101923. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\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};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,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#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,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}","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};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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);
  101924. globalObject["BABYLON"] = BABYLON;
  101925. 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 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 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 PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var 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 SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;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 VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  101926. 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,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,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,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,EnvironmentTextureTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleHelper,VideoDome,PhotoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };